CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 5 of 6 · 3 min read

wait and exit

wait and exit

In plain words: A process ends when it returns from main, calls exit, or is killed. At the end it leaves a small exit status: a number that tells the parent how it went. By convention 0 means success and anything else means failure.

The parent collects it with wait or waitpid. wait blocks until any child ends. waitpid(pid, &status, 0) waits for one chosen child. The status is a packed number, read with macros: WEXITSTATUS(status) gives the exit code if the child ended normally, and WIFSIGNALED(status) tells that a signal killed it. With WTERMSIG(status) one reads which signal. In the test above the child returned 7, so WEXITSTATUS printed 7.

A child that crashes also reports back. This child calls abort():

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
    pid_t p = fork();
    if (p == 0) { abort(); }
    int st;
    wait(&st);
    printf("signaled=%d sig=%d\n", WIFSIGNALED(st), WTERMSIG(st));
    return 0;
}

The result was signaled=1 sig=6, signal number 6, which is SIGABRT, the abort signal (page 6).

The calls exit and _exit differ in one way. exit runs cleanup first, such as flushing the C library's buffers. _exit leaves immediately. A child that calls exec and fails should use _exit, as above, so it does not flush a buffer it inherited from the parent and print text twice.

Waiting is also a duty: a parent that never waits leaves finished children as zombies (page 8).

Read it as

fork copies, exec replaces, exit finishes, wait collects. Every shell command you type uses all four.

Interview angle

Answer in your head first, then open it.

What does fork return?

The child's PID in the parent, 0 in the child, -1 on failure.

What happens to memory after fork?

The child gets its own copy, and changes in one are not seen by the other.

Why are fork and exec separate?

The child can set up redirection and other state between them.

How many processes after n unconditional forks?

2 to the power of n.

What does wait do?

It blocks until a child ends and returns its status.

Check yourself: 1. What does WEXITSTATUS give? 2. What is the difference between exit and _exit? 3. Which call tells you that a child was killed by a signal?

Words you will meet

Word Meaning
Parent, child The creator of a process, and the process it creates
fork Copy the calling process
exec Replace the program of the calling process
wait, waitpid Wait for a child to end and collect its status
Exit status The number a process leaves behind when it ends

Quick notes

  • fork is the Unix system call that creates a new process, the child, as a duplicate of the calling process, the parent.
  • exec is the family of system calls (execl, execvp, execve and others) that load a new program into the calling process.