Process Creation with fork, exec and wait

Every command you type in a Unix shell runs in a new process, and nearly every one of those processes is created the same way. An existing process copies itself with fork, the copy loads a new program with exec, and the original collects the result with wait. This lesson covers what each of these system calls does, what each returns, and how to count the processes a program creates.

fork: one call, two returns

fork() creates a child process that is a near-exact copy of the caller. The child has the same code, the same variable values and the same open file descriptors, and it continues from the same point: just after the call. Modern kernels avoid copying memory up front by using copy-on-write: parent and child share physical pages, and a page is duplicated only when one of them writes to it. From that point on, a write in one process is invisible to the other.


The two processes tell themselves apart only by the return value. The parent receives the child's PID, and the child receives 0:


Where the call returns

Value returned by fork()

Parent, on success

the child's PID, a positive integer

Child

0

Parent, on failure

-1, and no child exists


Because both processes continue from the same line, fork calls placed one after another multiply. If every process executes nn unconditional fork() calls in sequence, the number of processes doubles at each call:


Nprocesses=2n,Nchildren created=2n−1N_{\text{processes}} = 2^{n}, \qquad N_{\text{children created}} = 2^{n} - 1


Example: Two fork calls in a row give four processes. The original creates child A at the first call; at the second call the original creates child B and A creates a grandchild.



exec: replacing the program

The exec family (execl, execv, execvp and relatives) replaces the calling process's program image, meaning its code, data, heap and stack, with a new program loaded from disk. The PID, the parent and the open file descriptors stay the same, except descriptors marked close-on-exec. A successful exec never returns, so any statement after it runs only when exec fails.


C
pid_t pid = fork();                  /* error check omitted */
if (pid == 0) {                      /* child */
    char *args[] = {"ls", "-l", NULL};
    execvp("ls", args);
    perror("execvp");                /* reached only on failure */
    _exit(127);
}
int status;
waitpid(pid, &status, 0);            /* parent */
if (WIFEXITED(status))
    printf("exit code %d\n", WEXITSTATUS(status));


Timeline boxes showing a shell forking a child that execs ls and exits while the shell waits in waitpid.



wait: collecting the child

When a child terminates, the kernel frees its memory but keeps a small process-table entry holding its PID and exit status until the parent asks for it. A terminated child in this state is a zombie process. The parent reaps it with wait(&status), which waits for any child, or waitpid(pid, &status, 0), which waits for one specific child. Each successful call reaps exactly one child, so a parent that creates kk children needs kk successful waits to leave no zombies.


The status integer is decoded with macros. WIFEXITED(status) is true when the child called exit or returned from main, and WEXITSTATUS(status) gives only the low 8 bits of the value passed to exit, so exit(258) is reported as 2.


If the parent exits first, its children become orphans and are adopted by init (PID 1) or a designated subreaper, which reaps them when they end. A long-running server that never calls wait, however, accumulates zombies, each holding a process-table slot.

What to remember

  • fork() returns twice: the child's PID in the parent, 0 in the child, and -1 in the parent on failure.
  • nn unconditional sequential forks give 2n2^n processes and 2n−12^n - 1 new children.
  • exec replaces the program but keeps the PID and open descriptors; it returns only on error.
  • Each successful wait or waitpid reaps one child; terminated, unreaped children are zombies.
  • WEXITSTATUS reports the exit value modulo 256.

Example: Counting processes and output lines in a fork loop

The program below is compiled with the usual headers and run. Assume every fork() succeeds and ignore the order in which lines appear.


C
int main(void) {
    for (int i = 0; i < 3; i++) {
        if (fork() == 0)
            printf("i=%d\n", i);
    }
    printf("done\n");
    return 0;
}


a) How many processes, including the original, reach the final printf("done\n")?


A child does not leave the loop after printing; it carries on with the next iteration exactly like its parent. So every process that exists at the start of an iteration calls fork() once, and the number of processes doubles on each pass. One process enters iteration 0, ________ processes enter iteration 1, and ________ processes enter iteration 2. After the third fork the total is


N=23=8N = 2^{3} = 8


All 8 processes leave the loop and reach the final printf.


b) With stdout connected to a terminal, how many lines are printed in total?


A line of the form i=k is printed only by a process just created in iteration kk, because only the child sees fork() return 0. The number of children created in an iteration equals the number of processes entering it, so iteration 0 prints 1 line, iteration 1 prints ________, and iteration 2 prints ________:


1+2+4=7=23−11 + 2 + 4 = 7 = 2^{3} - 1


Each of the 8 processes also prints done once. On a terminal, stdout is line-buffered, so every complete line is written out immediately, before the next fork can copy it. The total is


7+8=15 lines7 + 8 = 15 \text{ lines}


c) The program is now run as ./a.out > out.txt. How many lines does out.txt contain?


When stdout is a file, it is fully buffered: nothing is written until each process returns from main and flushes its buffer. A child inherits a copy of its parent's unflushed buffer, so i=k lines already in the buffer are copied into every later descendant.


Describe each final process by the path it took. In each of the 3 iterations it was either the process that called fork (no print) or the newly created child (adds i=k to its buffer and carries it forward). The 8 final processes are the 232^3 combinations of these choices, and in each iteration exactly half of the paths took the child branch. Summed over all final buffers, the i=k lines number ________:


8×3×12=128 \times 3 \times \tfrac{1}{2} = 12


Each buffer also ends with one done line, adding 8 more:


12+8=20 lines12 + 8 = 20 \text{ lines}


The file holds 20 lines rather than 15 because 5 of the i=k lines were duplicated through inherited buffers. Calling fflush(stdout) before each fork restores the 15-line output.

A C program executes pid_t pid = fork(); and the call succeeds, so two processes continue from the next line. Which statement correctly describes the value stored in pid in each process?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A concurrent program built with fork, exec and wait produces processes that start, run alongside one another and terminate at different times. Match each term to the description that defines it.

Match each term
A.

The small integer a terminating process reports to its parent, decoded with WEXITSTATUS

B.

A child that has terminated but whose status has not yet been collected by its parent

C.

Parent and child share physical pages after fork until one of them modifies a page, when the kernel duplicates that page

D.

Collecting a terminated child's status with wait or waitpid so the kernel can free its process table entry

E.

An outcome that depends on how the scheduler happens to interleave the steps of concurrent processes

F.

A still-running child whose parent has already terminated, so init or a subreaper adopts it

Zombie process

Exit status

Reaping

Race condition

Copy-on-write

Orphan process

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Assume every fork() succeeds and stdout is a terminal. How many times does the following program print the letter x? Give your answer as a whole number.


C
int main(void) {
    fork();
    fork() && fork();
    printf("x\n");
    return 0;
}

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice