Skip to content
systemcoding.dev
Systems Programming

Create a Child Process in C with fork

Create a child process in C with fork on Linux, tell parent from child by the return value, and avoid the mistakes that run code twice.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and Linux logos.

A call to fork is the one place in a C program where a single line of code runs twice. After it returns, two processes exist, both executing the next statement, and the only way to tell them apart is the value fork gave back. This post builds a child process step by step with fork on Linux 6.12 and glibc 2.40, shows the three return cases, and covers the mistakes that make a program fork more often than you meant. The wider picture is in the complete guide to Unix processes.

The specification is in POSIX.1-2024, and Linux details are in the fork(2) man page.

The smallest working fork

Include <unistd.h> for fork and <sys/types.h> for pid_t. Store the result and branch on it:

fork_min.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0) {
        printf("in the child, pid %d\n", (int)getpid());
        _exit(EXIT_SUCCESS);
    }

    printf("in the parent, child is %d\n", (int)pid);
    waitpid(pid, NULL, 0);
    return EXIT_SUCCESS;
}

Compile it with gcc -std=c11 -Wall -Wextra -o fork_min fork_min.c. The two lines can appear in either order, because after fork the scheduler decides which process runs first. A typical run prints:

Text
in the parent, child is 30412
in the child, pid 30412

On another run the child line may come first. The parent calls waitpid so that the program does not exit before the child finishes, which also prevents the child from becoming a zombie. If you need a fixed order, you must create one with waitpid, a pipe or a signal, never by guessing at timing.

The three return values

fork returns a pid_t that means something different in each place:

WhereValueMeaning
Parentpositivethe process ID of the new child
Child0you are the child; use getppid() for the parent
Parent-1failure, no child exists, errno says why

The child's 0 is not a real process ID, which is why it works as a flag: no process has ID 0 as far as the caller is concerned. A child that needs its own ID calls getpid().

Failure is rare but real. EAGAIN means the per-user process limit (RLIMIT_NPROC) or the system-wide limit was reached, and ENOMEM means the kernel could not allocate the structures for the child. Always check for -1. If you skip the check and carry on, the value -1 flows into later calls like waitpid(-1, ...) and kill(-1, ...), where it means "any child" and "every process the caller may signal".

What the child gets

The child begins as a copy of the parent at the moment of the call: the same code, the same variables with the same values, the same open files and the same current directory. The copies then diverge. This program makes the divergence visible:

fork_copy.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    int balance = 100;

    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        balance -= 30;
        printf("child  balance = %d\n", balance);
        _exit(EXIT_SUCCESS);
    }

    waitpid(pid, NULL, 0);
    printf("parent balance = %d\n", balance);
    return EXIT_SUCCESS;
}
Text
child  balance = 70
parent balance = 100

The child's subtraction changed the child's copy only. This is the main difference from threads, where both threads would see 70. Linux achieves the copy cheaply with copy-on-write: parent and child share the same physical pages until one of them writes to a page, and only then does the kernel make a private copy of it.

What is shared and not copied matters just as much. Open file descriptors are duplicated, but each pair refers to the same open file description, so the file offset is shared. A parent and child that both write to the same descriptor interleave their output at one shared position instead of overwriting each other.

Why the child usually ends with _exit

The child inherits the parent's stdio buffers. If the parent has written text without a newline, the text is still sitting in memory, and both processes will try to flush it:

fork_buffer.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    printf("start ");
    pid_t pid = fork();
    if (pid == 0) {
        printf("child\n");
        exit(0);
    }
    waitpid(pid, NULL, 0);
    printf("parent\n");
    return EXIT_SUCCESS;
}

Run with the output sent to a file or a pipe, where stdio is fully buffered, start is flushed once by each process:

Text
start child
start parent

There are two fixes, and you should use both when the child does not call exec. Call fflush(stdout) before fork, and end the child with _exit so it skips the buffer flush and the atexit handlers that belong to the parent's state.

Forking more than once

A common mistake is to fork in a loop and forget that each child continues the loop. Three iterations do not create three children, they create a tree:

fork_bomb_safe.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    for (int i = 0; i < 3; i++) {
        pid_t pid = fork();
        if (pid < 0) {
            perror("fork");
            return EXIT_FAILURE;
        }
        if (pid == 0) {
            printf("child %d started by iteration %d\n", (int)getpid(), i);
            fflush(stdout);
            _exit(EXIT_SUCCESS);
        }
    }

    while (wait(NULL) > 0)
        ;
    puts("all children done");
    return EXIT_SUCCESS;
}

Because each child calls _exit instead of falling back into the loop, the program creates exactly three children. The order of the first three lines varies:

Text
child 31101 started by iteration 0
child 31102 started by iteration 1
child 31103 started by iteration 2
all children done

Remove the _exit and the first child continues to iteration 1, forks its own child, and so on: after three iterations you would have 2 to the power of 3, or eight processes, not four. The rule is simple. Every child must end in _exit or exec, so it can never return into the code meant for the parent. The loop while (wait(NULL) > 0) then reaps all of them and stops when wait returns -1 with ECHILD.

Giving each child its own job

A realistic use gives each child a unit of work and collects the results through exit codes. Exit codes carry only one byte, which is enough for pass or fail:

fork_jobs.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

static int check(int n)
{
    return n % 2 == 0 ? 0 : 1;
}

int main(void)
{
    pid_t pids[4];
    for (int i = 0; i < 4; i++) {
        pids[i] = fork();
        if (pids[i] < 0) {
            perror("fork");
            return EXIT_FAILURE;
        }
        if (pids[i] == 0)
            _exit(check(i));
    }

    for (int i = 0; i < 4; i++) {
        int status;
        waitpid(pids[i], &status, 0);
        printf("job %d: %s\n", i, WEXITSTATUS(status) == 0 ? "ok" : "failed");
    }
    return EXIT_SUCCESS;
}
Text
job 0: ok
job 1: failed
job 2: ok
job 3: failed

Saving the process IDs in an array lets the parent wait for each child by name, which keeps the report in job order even though the children may finish in any order. For larger results, children write to a pipe or a file, which later posts cover.

A check you can add while debugging

When a forked program behaves oddly, print the process ID at the top of each branch before anything else. Seeing two different IDs in the log tells you at once that both branches ran, and seeing the same ID twice tells you that something forked more often than you intended. Remove the prints when the flow is right, or keep them behind a debug flag, since stdout from two processes interleaves unpredictably.

When fork is the wrong call

fork is a good fit for a few children that run C code you control. It is a poor fit in three cases. If the goal is to run another program, fork followed by exec works, but posix_spawn expresses the same intent and avoids copying a large address space. If the program has several threads, the child gets only the calling thread and inherits any locks other threads held, so the child should do nothing but exec or _exit. And if you need thousands of concurrent tasks, a process per task is heavy; threads or an event loop are the usual answer.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.