Skip to content
Visual explainer 5h to learn 5 steps

fork, exec & wait

Launch a child program, wait for it and decode its exit status.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 15 of 42

In short

Unix creates processes in two steps: fork clones the calling process, and exec replaces the clone's program with a new one. The parent then calls wait or waitpid to block until the child ends and to collect its exit status. Every command you type in a shell runs through this pattern.

Think of it like this: fork photocopies a recipe card; exec rubs it out and writes a different recipe on the copy.

Explained simply

Unix starts a new program in two separate moves. First, fork makes a copy of the running process. Now there are two almost identical processes: the parent and the child. Second, the child calls exec, which throws away its own program and loads a new one in its place, keeping the same PID.

Why two steps? Because the gap between them is useful. After fork but before exec, the child can change things for the new program: redirect its output to a file, change directory, drop privileges or close files. The shell uses this gap every time you type a command with > or |.

Meanwhile the parent usually calls waitpid. This makes it pause until the child finishes, and then it receives a status number. That number tells the parent whether the child exited normally and with which code, or whether it was killed by a signal.

Copying a whole process sounds slow, but it is not. The kernel does not really copy the memory at fork time. Both processes share the same memory pages until one of them writes, and only then is that single page copied. This trick is called copy-on-write.

Press Play on a diagram to walk through it one step at a time.

SequenceRunning a command
Parent
Kernel
Child
  1. 1fork()
    Parent to Kernel: fork()
  2. 2returns the child's PID
    Kernel to Parent: returns the child's PID
  3. 3returns 0 in the child
    Kernel to Child: returns 0 in the child
  4. 4execvp("ls", argv): new program image
    Child to Kernel: execvp("ls", argv): new program image
  5. 5waitpid(pid, &status, 0) blocks
    Parent to Kernel: waitpid(pid, &status, 0) blocks
  6. 6exit(0)
    Child to Kernel: exit(0)
  7. 7waitpid returns with the exit status
    Kernel to Parent: waitpid returns with the exit status
CompareWhat survives exec
Kept
  • PID and parent PID
  • Open fds without FD_CLOEXEC
  • Current directory and umask
  • Signal mask and ignored signals
  • Resource limits
Replaced or reset
  • Code, heap, stack, mappings
  • All other threads
  • Caught signals go to default
  • fds marked FD_CLOEXEC are closed
  • atexit handlers are forgotten

In depth

What the child inherits, and what it does not

The child gets a copy of the parent's memory, a duplicate of the descriptor table, the same current directory, umask, signal handlers, signal mask, environment and resource limits. Duplicated descriptors point to the same open file, so parent and child share one file offset: if both write to the same file, their writes follow each other instead of overwriting.

Some things are not copied. The child has a new PID and its PPID is the parent. Pending signals are cleared, file locks taken with fcntl are not inherited, and timers are reset. Only the thread that called fork exists in the child. If another thread held a lock (for example inside malloc) at that moment, the lock stays locked forever in the child. That is why, in a multithreaded program, the child should only call async-signal-safe functions before exec.

  • Shared offset: parent and child appending to one log file works
  • fork in a threaded program: exec soon, call little else
  • fork returns -1 with EAGAIN when a process limit is reached

Copy-on-write under the hood

At fork the kernel copies the parent's page tables, not the pages. It marks every private writable page as read-only in both processes and counts how many processes use each page. When either process writes, the CPU raises a page fault. The kernel sees that the page is shared, allocates a new physical page, copies 4 KiB, maps the copy as writable for the writer, and lets the write continue.

The cost of fork therefore grows with the size of the page tables, not the memory. A 20 GB process can still take milliseconds to fork, which is why big programs such as databases prefer posix_spawn or vfork-style calls. glibc implements posix_spawn with clone and CLONE_VM | CLONE_VFORK, so the child borrows the parent's memory until it calls exec and no page tables are copied at all.

FlowA write after fork
  1. 1
    fork

    Page tables copied, pages marked read-only.

  2. 2
    Child writes

    CPU raises a page fault.

  3. 3
    Kernel checks

    Page is shared by two processes.

  4. 4
    Copy one page

    New 4 KiB page for the child only.

  5. 5
    Write continues

    Parent still sees its old data.

The exec family and what survives exec

There is only one real system call, execve(path, argv, envp). The library wrappers add letters: l means the arguments are listed one by one, v means they come in an array, p means search PATH for the program, and e means you pass your own environment. So execvp takes an array and searches PATH, while execle takes a list and an environment.

exec replaces the memory, the threads and the signal handlers (caught signals go back to their default action, because the handler code no longer exists). It keeps the PID, the parent, the current directory, the umask, the signal mask, ignored signals and every open descriptor that does not have the close-on-exec flag. Forgetting O_CLOEXEC is a classic way to leak a secret file or a listening socket into a child program.

waitpid in full

waitpid(pid, &status, options) chooses which child to wait for. A positive pid means that exact child, -1 means any child, 0 means any child in the caller's process group, and a value below -1 means any child in the group with that ID. The options WNOHANG (return 0 at once if nobody has finished), WUNTRACED (also report stopped children) and WCONTINUED (report resumed ones) change when it returns.

It returns the PID it collected, 0 with WNOHANG when no child is ready, or -1 with errno ECHILD when there are no children left, or EINTR when a signal handler interrupted it. Decode the status with macros only: WIFEXITED and WEXITSTATUS, WIFSIGNALED and WTERMSIG, WIFSTOPPED and WSTOPSIG. Only the low 8 bits of an exit code survive, so exit(256) looks like exit(0) to the parent.

  • Shells show death by signal N as exit code 128+N (Ctrl-C gives 130)
  • WCOREDUMP(status) is true when a core file was written
  • waitid() is the newer, more detailed variant

Conventions that make tools behave

Exit codes carry meaning by convention: 0 is success, 1 is a general error, 2 is often bad usage, 126 means the program was found but could not be executed, and 127 means it was not found. Make your child use 127 after a failed exec, just like a shell, so scripts can tell what went wrong.

Two more habits prevent strange bugs. Call fflush(NULL) before fork, or the child inherits unwritten stdio buffers and prints them a second time. And after a failed exec in the child, call _exit, not exit, so the child does not run the parent's atexit handlers or flush the parent's buffers again. Always check fork for -1; on a busy server it really happens.

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create a child with fork~1h
  2. 2
    Replace the image with execvp~1h
  3. 3
    Reap children with waitpid~1h
  4. 4
    Decode status with WIFEXITED and WEXITSTATUS~1h
  5. 5
    Explain copy-on-write after fork~1h

Key points

  • fork returns twice: the child's PID in the parent, 0 in the child, or -1 on error.
  • Memory is shared copy-on-write, so fork is cheap until someone writes.
  • exec only returns on failure, so code after it runs only if exec failed.
  • Decode the status from waitpid with WIFEXITED and WEXITSTATUS.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); return 1; }
  if (pid == 0) {
    char *argv[] = { "ls", "-l", NULL };
    execvp(argv[0], argv);
    perror("execvp"); _exit(127);
  }
  int status; waitpid(pid, &status, 0);
  if (WIFEXITED(status)) printf("child exited %d\n", WEXITSTATUS(status));
  return 0;
}

The fork, exec, wait pattern every shell uses.

A tiny "run" command that reports how a child ended

This program runs whatever command you give it and explains how it finished. Step 1: fork and check for -1. Step 2: the child execs the command with execvp; if that fails it prints why and exits with 127. Step 3: the parent waits, retrying if a signal interrupts the wait. Step 4: it decodes the status. Try ./run true, ./run false, ./run nosuchcmd and ./run sleep 60 while you send kill -TERM to the sleep from another terminal.

c
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  if (argc < 2) { fprintf(stderr, "usage: %s cmd [args...]\n", argv[0]); return 2; }
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); return 1; }
  if (pid == 0) { execvp(argv[1], &argv[1]); perror(argv[1]); _exit(127); }
  int st;
  while (waitpid(pid, &st, 0) < 0) if (errno != EINTR) { perror("waitpid"); return 1; }
  if (WIFEXITED(st)) printf("exited with %d\n", WEXITSTATUS(st));
  else if (WIFSIGNALED(st)) printf("killed by signal %d\n", WTERMSIG(st));
  return 0;
}

Why does my output appear twice?

The program below prints hello once on a terminal but twice when you run ./a.out > out.txt. On a terminal stdout is line-buffered, so the text with a newline is written before fork. In a file it is fully buffered, so hello is still sitting in the buffer when fork copies the memory, and both processes flush it at exit. The fix is one line: fflush(NULL) right before fork.

c
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
  printf("hello\n");
  /* fflush(NULL);   <- uncomment to fix */
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); return 1; }
  if (pid > 0) waitpid(pid, NULL, 0);
  return 0;   /* both processes flush stdout here */
}

Quick reference

  • fork returns the child's PID in the parent, 0 in the child, -1 on error
  • exec letters: l list, v vector, p search PATH, e custom environment
  • Only execve is a real system call; the others are library wrappers
  • Open fds survive exec unless they have O_CLOEXEC or FD_CLOEXEC
  • waitpid(-1, &st, WNOHANG) reaps any finished child without blocking
  • Exit 126: found but not executable; 127: command not found; 128+N: killed by signal N
  • Call fflush(NULL) before fork and _exit after a failed exec
  • strace -f -e trace=clone,execve,wait4 ./prog shows the whole pattern

Common mistakes

  • Calling exit instead of _exit in a child after a failed exec, which flushes copied stdio buffers twice.
  • Never calling wait, which leaves zombie processes behind.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Parent and child both write to a file descriptor that was open before fork. What happens to the file offset?

Question 2

2What happens to a signal handler installed with sigaction after a successful exec?

Question 3

3What does waitpid return when called with WNOHANG and no child has finished yet?

Question 4

4Why is fork fast even for a process using several gigabytes of memory?

Question 5

5A child calls exit(300). What does WEXITSTATUS give the parent?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a program that forks once; the child prints its PID and PPID, the parent prints the child's PID and waits for it.

  2. Exercise 2medium

    Start 5 children that each sleep a random 1 to 3 seconds and exit with their index. The parent must reap them in the order they finish and print each index.

  3. Exercise 3hard

    Run ls -l with its output written to listing.txt, doing the redirection yourself between fork and exec. Make sure the file is not leaked to any other program.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why doesn't Unix have a single "create process" call?
It does now (posix_spawn), but fork plus exec is kept because the gap between them lets the child set up redirection, directories and permissions using ordinary calls.
Should I use fork or posix_spawn?
For simply launching a program, posix_spawn is often faster and safer in large or multithreaded programs. Use fork when the child must run your own code or needs setup that posix_spawn cannot express.
Why does code after execvp run?
Because execvp failed; on success it never returns. Print the error with perror and exit the child with _exit(127).
What is the difference between wait and waitpid?
wait(&st) waits for any child. waitpid lets you choose a specific child or group and pass options like WNOHANG.

Go deeper

ShareXLinkedInWhatsApp