fork, exec and wait from the kernel's side
About this lesson
Every command you type in a shell starts a new program, and it always happens the same way: three system calls. fork() asks the kernel to copy the calling process, exec() swaps the program inside a process for a new one, and wait() lets the parent collect the child's result. Follow one short C program through the kernel's process table as a PCB is copied, fork returns twice, the child becomes /bin/echo without changing its ID, and a zombie waits to be collected. The lesson The process: address space, registers and the PCB introduces the PCB, and Process states: ready, running and blocked explains the states you will see change here. The Linux lesson on processes and signals shows the same ideas from the command line.
One program starts another
A running program can start another with three system calls. fork() copies the calling process. exec() swaps the program inside a process for a new one. wait() lets the first process collect the result. Each is work the kernel does.
fork() copy me: a new process, the child
exec() replace my program with another one
wait() sleep until my child ends, then get its result
the whole program (C99, POSIX):
#define _POSIX_C_SOURCE 200809L /* fork, execvp, waitpid under -std=c99 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
char *argv[] = {"echo", "hi", NULL};
pid_t pid;
int status;
pid = fork();
if (pid == 0)
execvp("echo", argv);
waitpid(pid, &status, 0);
if (pid == 0) return 127; /* only if exec failed */
printf("exit %d\n", WEXITSTATUS(status));
return 0;
}Read the lesson step by step
One program starts another
A running program can start another with three system calls. fork() copies the calling process. exec() swaps the program inside a process for a new one. wait() lets the first process collect the result. Each is work the kernel does.
fork() copy me: a new process, the child exec() replace my program with another one wait() sleep until my child ends, then get its result the whole program (C99, POSIX): #define _POSIX_C_SOURCE 200809L /* fork, execvp, waitpid under -std=c99 */ #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main(void) { char *argv[] = {"echo", "hi", NULL}; pid_t pid; int status; pid = fork(); if (pid == 0) execvp("echo", argv); waitpid(pid, &status, 0); if (pid == 0) return 127; /* only if exec failed */ printf("exit %d\n", WEXITSTATUS(status)); return 0; }The kernel keeps a record
Our program runs as process 100. For each process the kernel keeps a record called a PCB (process control block) in its process table: the ID, the state (now running), the saved registers and where its memory is.
PCB 100 (process control block) PID 100 state running (running, ready, blocked, ...) registers saved here while it is not running memory where its code and data are files its open files: 0, 1, 2 process table = all the PCBsLine 1: fork()
Line 1 calls fork(). Like every system call it traps into the kernel, which now works on behalf of process 100.
line 1 pid = fork(); process 100 asks the kernel: copy me trap user mode -> kernel modeThe kernel copies the process
The kernel makes a new PCB with a new ID, 101, and copies the parent into it: its memory, its open files and its saved registers. The child is a near twin, ready to run the same code from the same spot.
new PCB PID 101 state ready memory a copy of 100's (Linux: copy-on-write) files copies of the open file descriptors registers copied: both will carry on after fork() parent PID 100 is the child's parentfork() returns twice
fork() returns twice, once in each process. The parent gets the child's ID, 101. The child gets 0. That is the only difference, and line 2, if (pid == 0), uses it to choose a path.
in the parent pid = 101 (the child's PID) in the child pid = 0 (I am the child) on error -1 in the parent, and no child which one runs first is up to the scheduler; here the parent doesThe parent waits
In the parent pid is 101, not 0, so it skips line 3 and calls waitpid(). The child has not finished, so the kernel marks the parent blocked: it uses no CPU. The kernel runs the child instead.
line 4 waitpid(pid, &status, 0); child 101 not finished yet PCB 100 running -> blocked PCB 101 ready -> runningThe child calls exec()
In the child pid is 0, so it runs line 3, execvp(). The kernel throws away the child's memory, loads /bin/echo from disk in its place and starts it. Same process, same ID 101: only the program changed.
line 3 execvp("echo", argv); argv {"echo", "hi", NULL} execvp finds echo on the PATH, e.g. /bin/echo memory old code, data, heap and stack thrown away new ones loaded from the file PID 101 (unchanged: no new process) program a.out -> /bin/echoecho runs and exits
echo prints hi, then calls exit(0). Notice that execvp() never returned: the code that called it no longer exists. On success exec has nowhere to return to.
echo write(1, "hi\n", 3) -> screen: hi exit(0) -> kernel exec returns only if it failed (then -1); the full program then ends with 127A zombie, and a wake-up
The kernel frees the child's memory and files, but keeps its PCB holding the exit status, 0. A finished process whose status nobody has collected yet is a zombie. The kernel also wakes the parent: blocked becomes ready.
PCB 101 running -> zombie keeps: PID, exit status 0, usage memory and files freed PCB 100 blocked -> ready (its child changed state)wait() collects the result
When the parent runs again, waitpid() returns 101 and puts the exit status in status. Now the kernel deletes the zombie's PCB: the child is gone for good. The parent prints exit 0.
waitpid returns 101 status = 0 PCB 101 deleted (the child is reaped) PCB 100 running printf exit 0 (WEXITSTATUS(status)) screen: $ ./a.out hi exit 0Why two calls, not one?
Between fork() and exec() the child still runs the parent's code, so it can change its own setup first, such as sending its output to a file. A shell runs every command you type this way.
$ echo hi > out.txt the shell: fork() child: close stdout, open out.txt (fd 1) child: exec("echo") -> hi goes to the file wait() then show the next prompt the story as a Python simulation: table = {} # the kernel's process table def fork(parent, pid): # a new PCB, a copy of the memory table[pid] = dict(table[parent], state="ready") return pid, 0 # parent sees pid, child sees 0 def exec_(pid, program): # same PCB and PID, new program table[pid]["program"] = program def exit_(pid, status): # memory freed, PCB kept: zombie table[pid].update(state="zombie", status=status) def wait(parent, child): # collect the status, delete the PCB table[parent]["state"] = "running" return child, table.pop(child)["status"] table[100] = {"state": "running", "program": "a.out"} in_parent, in_child = fork(100, 101) print("fork returned", in_parent, "and", in_child) table[100]["state"] = "blocked" # waitpid: the child is not done exec_(101, "/bin/echo") print(101, "now runs", table[101]["program"]) exit_(101, 0) print("wait returned", wait(100, 101), "table", sorted(table)) prints: fork returned 101 and 0 101 now runs /bin/echo wait returned (101, 0) table [100]
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A process with PID 100 calls fork() and the kernel creates PID 101. What does fork() return?
fork() returns twice. The parent gets the new child's PID so it can wait for it; the child gets 0, which is how the code tells the two apart.
02Right after fork(), what does the child have?
The child is a near copy of the parent: memory (copy-on-write on Linux), open file descriptors and saved registers, so it carries on from the same spot. Its PID and PCB are new.
03Process 101 calls execvp("echo", argv) and it succeeds. What is true afterwards?
exec does not create a process. The kernel replaces the memory of the same process with the new program and starts it; the code that called exec is gone, so there is nothing to return to. It returns -1 only if it fails.
04The child has exited but its parent has not called wait() yet. What is the child now?
The kernel frees the child's memory and files but keeps a small record (PID, exit status, resource usage) so the parent can still read the result. That leftover is the zombie.
05Why are fork() and exec() two separate calls?
Between fork and exec the child still runs the shell's code, so it can close and reopen standard output, set up a pipe and so on. The new program then inherits that setup. This is how a shell runs echo hi > out.txt.
Glossary
- Process
- A running program: its memory, its open files and its place in the CPU, managed by the kernel.
- PID
- Process ID: the number the kernel gives each process, such as 100 or 101.
- PCB
- Process control block: the kernel's record for one process, holding its PID, state, saved registers and where its memory is. All the PCBs together form the process table.
- fork()
- A system call that makes a new process, the child, as a copy of the calling process, the parent. It returns the child's PID in the parent and 0 in the child.
- exec()
- The execve system call and its library front-ends (execvp, execl, ...), which replace the program running in the calling process with a new program from a file. The PID stays the same.
- wait()
- A system call (also waitpid) that blocks the parent until a child ends, then returns the child's PID and exit status.
- Zombie
- A process that has finished but whose exit status its parent has not collected yet. Only its PCB remains.
- Exit status
- The small number a program ends with, such as exit(0). By convention 0 means success.
Notes and sources
- The PIDs 100 and 101 are made up for the example. Linux hands out the next free number, counting up from the last one used and wrapping around at pid_max, so real PIDs depend on what else has run.
- Each card shows the same four lines of main(). The whole program also declares argv, pid and status, and prints exit 0 at the end; if exec ever failed, the child would end with 127 instead.
- Copying a whole memory would be slow, so Linux uses copy-on-write: after fork both processes share the same pages, marked read-only, and a page is copied only when one of them writes to it. The lesson draws the copy as if it were made at once.
- After fork, either process may run first: the scheduler decides. Here the parent runs first and blocks in waitpid(). If the child ran first and had already exited, waitpid() would find the zombie and return at once. The result is the same.
- The child also gets copies of the parent's open file descriptors, and they stay open across exec unless marked close-on-exec. That is how echo writes to the same screen as its parent.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 5: Interlude: Process API
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 4: The Abstraction: The Process
- Berkeley CS162, Lecture 3: the process control block
- MIT 6.1810, xv6: a simple, Unix-like teaching operating system (book, rev. 4)
- Linux man-pages: fork(2)
- Linux man-pages: execve(2)
- Linux man-pages: exec(3)
- Linux man-pages: wait(2)
- Linux kernel documentation: /proc/sys/kernel (pid_max, ns_last_pid)
Quiz Unlocks after the last step.