Skip to main content

Lesson 3 of 26 · 12 min read

The UNIX process API: fork, exec, and wait

Trace why UNIX splits process creation into fork() and exec(), how wait() orders parent and child execution, and why shell redirection works.

Shell command launch flow: fork() clone, Redirect FD, exec() image, and wait() reap.
Splitting fork() from exec() creates the window where shells set up pipes and redirection safely.
Course syllabus · lesson 3 of 26
In this lesson

OSTEP Chapter 5 design question — Why split process creation from program replacement? A shell needs to set up a command's standard streams, arguments, and execution environment before that command runs. The separation between fork and exec gives the shell a place to apply that setup in the child. wait lets it collect the outcome afterward. Chapter 5 frames this question in its API motivation section.

Take wc -l notes.txt > out.txt. The shell parses the redirection itself and runs wc with arguments wc, -l, and notes.txt. The command can use the same standard-output code it uses at a terminal. Its descriptor table already points output at the file by the time its first instruction runs.

Parent shell calls fork(), waits on the child, while the child redirects stdout to out.txt, calls exec('wc'), and the parent reaps exit status via wait().
Open full-size diagram
Splitting fork() from exec() gives the child a safe window to rewire file descriptors before the target program starts.

Trace fork, exec, and wait

Shell fork(), Parent shell, Child creatingShellfork()ParentshellChildcreating

Step 1 of 4

Enter fork()

The shell calls fork(). The kernel creates a child with its own PID and a logical copy of the parent’s address space.

One fork call, two continuations

fork() creates a child process. After success, the parent observes a positive return value equal to the child's PID, while the child observes zero. On failure the caller gets -1 and there is no child. Code that lumps a failed fork into the parent success branch might wait for an unrelated child or try to signal an unintended group based on an invalid identifier.

The kernel gives the child enough execution state to reach the same continuation after the syscall. Its saved user program counter and stack state start from the parent's. The return-value slot in the child's saved registers is set to zero. The parent's return-value slot receives the new PID. Each process can then run the same conditional and take its own branch. Neither branch gets priority merely because of its position in the source.

The child sees the parent's private memory as of the fork. A copy-on-write implementation can initially share physical pages, with private writable mappings protected so a later store triggers creation of a private copy when needed. Assume a parent and child initially share a page containing a variable whose value is 7. If the child writes 9 to its private mapping, the parent can still read 7. A mapping created explicitly for shared writes has different semantics. Virtual address equality across the two processes does not establish that writes are shared.

User-space buffers are part of memory too. Consider a printf before fork with output redirected to a file. If the library still holds those bytes in its buffer, both copies receive the pending text. If both call exit and flush, the line can appear twice. An explicit flush before forking sends the line once. An exec-failure path in a child commonly uses _exit to avoid flushing copied buffers or running the parent's exit handlers.

Descriptors and open file descriptions

What the child inherits depends on the type of state. Descriptor entries belong to each process. An entry refers to a kernel open file description, which carries the current file offset and file status flags. The parent and child initially hold references to the same descriptions. Closing an entry in the child removes its reference without clearing the parent's slot. Advancing a shared description's offset can affect the next read by either process.

For example, open a seekable file before forking with an initial offset of 0. If the child reads 4 bytes and the parent then reads 2 bytes through the inherited description, their reads cover offsets 0 through 3 and 4 through 5. The offset is then 6. If the child opens the same path again, that new open has an independent file offset, initially 0. Both opens can still refer to the same underlying file data. This distinction also applies when two descriptors in one process are created from one open description with dup2.

A close-on-exec flag lives on a descriptor entry. A successful exec closes entries with that flag and retains the others. This lets a shell pass standard streams to the command while keeping unrelated resources out of the new image. A leaked pipe endpoint can also affect correctness. A reader sees end-of-file only after every reference to the write endpoint has been closed and its buffered bytes have been read.

What exec replaces

The exec family replaces the calling process's program image. It establishes the new mappings, stack, and starting instruction address. An argument vector is a sequence of pointers to strings ending in a null pointer. execve takes that vector and an environment vector directly. execvp searches PATH for a name with no slash and uses the current environment.

The caller retains its PID and its relationship to its parent. Open descriptors survive according to their close-on-exec flags. If execvp succeeds, the old image never resumes. The error branch after the call is therefore reachable only on failure. A shell must report that error and terminate the child. Otherwise a child could fall into code intended for the original shell and reach a second prompt.

The launch sequence matters. Before fork, a redirection applied to the shell's own descriptor table would change where the shell prints. After successful exec, the wrapper has no chance to apply the redirection at all. Between the calls, it can change the child table and then let the new program inherit those changes.

The same ordering lets a shell connect two commands with a pipe. The shell creates the pipe before forking so both children inherit its read and write descriptors. The producer duplicates the write end onto standard output, and the consumer duplicates the read end onto standard input. Each child closes the unneeded original endpoints before exec. The parent closes both of its own endpoints after launching the children. If it waits for the producer before starting the consumer, a producer that fills the pipe can block waiting for a reader that has yet to launch. If the parent keeps the write end open while waiting for the consumer, that consumer can block waiting for end-of-file. The descriptor references determine when each side can finish.

A foreground command in C

The example assumes standard input, output, and error are all open on entry and a single-threaded launcher. The additive flag expression follows the distinct flag bits on the target Unix. Writing O_WRONLY first selects the access mode, then the other terms request creation and truncation.

Code exampleC
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t child = fork();
    if (child < 0) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (child == 0) {
        int flags = O_WRONLY + O_CREAT + O_TRUNC;
        int fd = open("out.txt", flags, 0666);
        if (fd < 0) {
            perror("open out.txt");
            _exit(1);
        }
        if (dup2(fd, STDOUT_FILENO) < 0) {
            perror("dup2");
            _exit(1);
        }
        close(fd);

        char *args[] = {"wc", "-l", "notes.txt", NULL};
        execvp(args[0], args);
        perror("execvp wc");
        _exit(126);
    }

    int status;
    pid_t result;
    do {
        result = waitpid(child, &status, 0);
    } while (result < 0 && errno == EINTR);
    if (result < 0) {
        perror("waitpid");
        return EXIT_FAILURE;
    }
    if (WIFEXITED(status))
        return WEXITSTATUS(status);
    if (WIFSIGNALED(status))
        return 128 + WTERMSIG(status);
    return EXIT_FAILURE;
}

open takes the lowest free slot, ordinarily 3 here. It requests mode 0666 for a new file before the process's umask removes permission bits. Opening an existing writable out.txt with O_TRUNC can empty it immediately. If wc later fails to launch or to read its input, the file can already be empty. Opening first also lets the child report a file error before it tries to run the command.

dup2 places the open file reference at the exact destination, replacing the old standard-output entry as part of the operation. close(fd) then releases the extra reference. Reversing those lines would invalidate the source descriptor. The assumption that the standard slots are open guarantees fd differs from 1. A more general launcher guards the close with if (fd != STDOUT_FILENO) because dup2(1, 1) leaves the existing entry alone. Standard error still points at whatever the launcher inherited, so redirection setup errors can appear separately from command output.

The last entry of args tells exec where the arguments end. Redirection operators are gone, having been interpreted by the launcher. If exec returns, the diagnostic identifies the command that failed to start and _exit ends that branch. The example uses a simple convention for launch failures. A full shell can distinguish more cases, including a command name it cannot find.

Waiting for exactly one child

The parent calls waitpid with the specific PID. If the child is still running, the parent can sleep. If the child has already exited, the kernel can return the recorded status immediately and reap it. The order of the first dispatch after fork does not change what success means for the wait. A plain wait can collect any waitable child, which matters if another command is running in the background.

A signal can interrupt a blocking wait and return EINTR before a child has been collected. Retrying lets an ordinary interruption preserve the foreground wait. Check for a successful wait before inspecting status because failure can leave it unusable. The status encodes how the child ended. WIFEXITED must be true before reading WEXITSTATUS, and WIFSIGNALED guards WTERMSIG. The example maps a signal termination to the familiar shell convention of 128 plus the signal number.

Waiting imposes an ordering between child termination and the parent's next action. It does not make the child run before the parent reaches the wait, and it does not itself flush file contents to persistent storage. A background launcher may defer collection, but it must eventually handle child termination to avoid accumulating zombies.

Worked trace

Suppose a launcher has PID 100, with entries 0, 1, and 2 connected to the terminal. Assume notes.txt contains two newline-terminated lines and the next fork creates PID 101.

  1. Both processes continue after fork. PID 100 observes 101 and enters waitpid. PID 101 observes 0 and goes into the setup branch with references to the inherited terminal descriptions.
  2. PID 101 opens out.txt. Its entry 3 now refers to a new description at offset 0. Entry 1 still refers to the terminal until dup2(3, 1) succeeds.
  3. After dup2, entries 1 and 3 in PID 101 refer to the output description. Closing entry 3 leaves the reference in entry 1. PID 100's entry 1 still refers to the terminal.
  4. Exec replaces PID 101's image and preserves entries 0, 1, and 2. wc opens its input and writes a count of two, possibly with a filename and formatting, through entry 1. Its diagnostic path still uses entry 2.
  5. PID 101 exits successfully. PID 100 returns from the wait with PID 101 and can extract exit status 0. If PID 101 had completed before PID 100 ran, the wait would collect the same status without sleeping.

Change one input

Remove only the dup2 call and keep the remaining successful operations in order. Opening the destination can still truncate it, and closing descriptor 3 removes the only reference the child created to that open description. When wc writes the count, descriptor 1 still leads to the terminal. Predict the outcome before running the example. The file remains empty even though the command can exit successfully.

Next, examine limited direct execution, traps, and context switches.

Before you move on

Try it in your workspace

Follow fork(), exec(), and wait() in a shell launching `wc -l notes.txt > out.txt`. Sketch which file descriptors stay open between fork() and exec() so redirection works cleanly.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.