When you type ls in a Linux terminal and press Enter, a new process appears, prints a list of files and disappears. Where did that process come from? Who created it, and how did it end up running the ls program?
On Unix-like systems (Linux, macOS, Android, the BSDs), the answer is a pair of system calls that every OS student must know:
fork()→ creates a new process that is a copy of the callerexec()→ replaces the program running inside a process with a new program
Plus their partner wait(), which lets a parent wait for its child to finish and collect its exit status.
fork() makes a copy of a process. exec() changes what program a process is running. A shell runs a command by doing fork, then exec in the child, then wait in the parent.
In this chapter we will run real C programs on Linux to see exactly how these calls behave, solve the famous "how many times does this print?" puzzles, and understand zombie and orphan processes.
Parent and Child Processes
Every process (except the very first one) is created by another process. The creator is the parent; the new process is the child. Children can create their own children, so processes form a tree.
systemd / init (PID 1)
├── sshd
│ └── bash
│ ├── vim notes.txt
│ └── ls -l
├── cron
└── mysqld
On Linux, the kernel starts the first user process, init (on most modern distributions this is systemd), with PID 1. Everything else descends from it. You can see your own tree with the pstree command.
Each process has a PID (process ID) and remembers its parent's PID, the PPID. In C, getpid() and getppid() return them. As we saw in Process Control Block & Context Switching, both are stored in the process's PCB.
fork(): One Call, Two Returns
fork() creates a new child process that is an almost exact copy of the parent: same code, same values in variables, same open files, and it continues from the same point in the program, right after the fork() call.
So after fork() returns, two processes are running the same code. How do they know who is who? By the return value:
Return value of fork() | Meaning |
|---|---|
0 | You are the child |
Positive number | You are the parent; the number is the child's PID |
-1 | fork failed (no child was created), e.g. too many processes |
Why does the parent get the child's PID, but the child gets 0? A parent can have many children, so it needs each child's PID to manage them (wait for them, send signals). A child has exactly one parent and can always find it with getppid(), so it does not need anything extra.
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
printf("Before fork: I am PID %d\n", getpid());
fflush(stdout);
pid_t pid = fork();
if (pid < 0) { /* fork failed */
perror("fork");
return 1;
} else if (pid == 0) { /* this branch runs in the CHILD */
printf("Child : fork() returned %d, my PID = %d, my parent = %d\n",
pid, getpid(), getppid());
} else { /* this branch runs in the PARENT */
printf("Parent: fork() returned %d (the child's PID), my PID = %d\n",
pid, getpid());
wait(NULL); /* wait for the child to finish */
}
return 0;
}
Compile and run on Linux:
gcc -std=c17 -Wall -Wextra fork1.c -o fork1
./fork1
Output (one run):
Before fork: I am PID 14986
Child : fork() returned 0, my PID = 14987, my parent = 14986
Parent: fork() returned 14987 (the child's PID), my PID = 14986
Things to notice:
"Before fork" is printed once, because only one process existed at that point.
After the fork, both branches of the
ifrun, but in different processes.The child's parent (14986) is the parent's PID, and the parent's
fork()returned the child's PID (14987).The PIDs will be different on your machine.
Important: after
fork(), parent and child run concurrently. The order of their output is decided by the scheduler and is not guaranteed. On some runs, the parent's line can appear before the child's line. If you need an order, you must synchronize, for example withwait().
The Child Gets a Copy, Not a Share
After fork(), the child has its own copy of the parent's memory. Changing a variable in one process does not affect the other.
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int x = 10;
pid_t pid = fork();
if (pid == 0) { /* child */
x = x + 5;
printf("Child : x = %d, &x = %p\n", x, (void *)&x);
return 0;
}
wait(NULL); /* let the child finish first */
x = x - 5;
printf("Parent: x = %d, &x = %p\n", x, (void *)&x);
return 0;
}
Output:
Child : x = 15, &x = 0x7fff48a74bd0
Parent: x = 5, &x = 0x7fff48a74bd0
Both processes started with x = 10. The child added 5 and the parent subtracted 5, and neither saw the other's change.
But look at the addresses: they are the same! How can two different variables have the same address? Because these are virtual addresses. Each process has its own virtual address space, and the same virtual address is mapped to different physical memory in each process. You will understand this fully in Paging and Virtual Memory & Demand Paging.
Copy-on-Write: Why fork() Is Fast
If fork() really copied all of a large process's memory (say 2 GB), it would be very slow. And it would often be wasted effort, because the child usually calls exec() immediately and throws that memory away.
Modern systems use copy-on-write (COW):
At fork time, the child gets a copy of the parent's page tables, not of the memory. Both processes point to the same physical pages.
Those shared pages are marked read-only.
When either process tries to write to a page, the CPU raises a fault. The kernel then makes a private copy of just that page for the writer and lets the write continue.
Right after fork():
Parent's page table ──┐
├──▶ [A] [B] [C] (physical pages, shared,
Child's page table ──┘ marked read-only)
After the child writes to page B:
Parent's page table ───▶ [A] [B] [C]
Child's page table ───▶ [A] [B'] [C] B' = child's private copy;
A and C are still shared
Pages that are never written are never copied. So the program behaves as if the memory was copied, but the real copying is lazy.
Classic Puzzle: How Many Processes?
These questions appear in almost every OS exam and interview. The key rule:
Each fork() call doubles the number of processes that execute it. Every process that reaches a fork() creates one child, and both continue from the next statement.
Puzzle 1: Three forks in a row
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
fork();
fork();
fork();
printf("hello from PID %d\n", getpid());
while (wait(NULL) > 0) /* each process waits for its own children */
;
return 0;
}
Trace:
Start: 1 process
After 1st fork(): 2 processes (each of them runs the 2nd fork)
After 2nd fork(): 4 processes (each of them runs the 3rd fork)
After 3rd fork(): 8 processes
Output (one run):
hello from PID 15017
hello from PID 15016
hello from PID 15019
hello from PID 15018
hello from PID 15014
hello from PID 15015
hello from PID 15013
hello from PID 15012
"hello" is printed 8 = 23 times. In general, n consecutive fork() calls give 2n processes in total, of which 2n − 1 are newly created children. Notice that the PIDs appear in a jumbled order: the scheduling order is not deterministic.
Puzzle 2: fork() in a loop
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
for (int i = 0; i < 3; i++) {
if (fork() == 0) {
printf("new child created at i = %d\n", i);
fflush(stdout); /* empty the buffer before the next fork */
}
}
while (wait(NULL) > 0)
;
return 0;
}
Here only the child prints. Children also continue the loop, so they fork too. We counted the lines with ./forkloop | sort | uniq -c:
1 new child created at i = 0
2 new child created at i = 1
4 new child created at i = 2
At i = 0 there is 1 process, so 1 child is created. At i = 1 there are 2 processes, so 2 children. At i = 2 there are 4 processes, so 4 children. Total children = 1 + 2 + 4 = 7 = 23 − 1.
Why the fflush(stdout)? Read the section on buffered output below: without it, this exact program printed 12 lines instead of 7 when its output went into a pipe.
Puzzle 3: fork() with && and ||
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
if ((fork() && fork()) || fork()) {
/* nothing: we only care how many processes exist */
}
printf("X\n");
while (wait(NULL) > 0)
;
return 0;
}
Output:
X
X
X
X
X
Five processes print "X". To see why, remember that && and || use short-circuit evaluation: A && B skips B if A is 0 (false), and A || C skips C if A is non-zero (true). Also remember that fork returns non-zero (true) in the parent and 0 (false) in the child.
P (original)
│ first fork() → P gets non-zero, so it evaluates the second fork()
├── C1 gets 0 → (0 && ...) is false, so C1 evaluates the third fork()
│ └── C3 (third fork, in C1)
│
│ second fork() → P gets non-zero → (A && B) is true → skip third fork
└── C2 gets 0 → (A && B) is false, so C2 evaluates the third fork()
└── C4 (third fork, in C2)
Processes: P, C1, C2, C3, C4 → 5 processes, 5 X's
A Hidden Trap: Buffered Output and fork()
This one surprises even experienced programmers.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
printf("Hello\n");
fork();
printf("Bye\n");
while (wait(NULL) > 0)
;
return 0;
}
Run it in a terminal:
Hello
Bye
Bye
Now run it again, but redirect the output into a file (./fork5 > out.txt; cat out.txt):
Hello
Bye
Hello
Bye
"Hello" appears twice, even though it was printed before the fork! Why?
printfdoes not write to the screen immediately. It puts the text into a buffer inside the process's memory (the C standard library'sstdiobuffer).When stdout is a terminal, the buffer is flushed at every newline, so "Hello\n" is written out before the fork.
When stdout is a file or pipe, the buffer is flushed only when it is full or the program exits. So "Hello\n" is still sitting in the buffer at fork time.
fork()copies the whole memory, including the unflushed buffer. Both processes later flush their copy, so "Hello" is written twice.
The fix is to call fflush(stdout) before fork(). This is why many examples in this tutorial flush before forking.
exec(): Replacing the Program
fork() gives you a copy of the same program. To run a different program, a process calls one of the exec functions. exec:
loads a new program from disk into the current process,
throws away the old code, data, heap and stack,
starts executing the new program's
main().
The PID stays the same: it is the same process, just running a different program. And if exec succeeds, it never returns, because the code that called it no longer exists.
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("Before exec: PID %d\n", getpid());
fflush(stdout);
/* Replace this program with the shell "sh", asking it to print its PID */
execlp("sh", "sh", "-c", "echo After exec: PID $$, now running sh", (char *)NULL);
/* We reach here ONLY if exec failed */
perror("execlp");
return 1;
}
Output:
Before exec: PID 15047
After exec: PID 15047, now running sh
The shell sh printed its own PID using $$, and it is the same PID as before. The line perror("execlp") was never reached.
The exec Family
There is one real system call, execve(); the others are library wrappers around it. Their names tell you how they take arguments:
Letter | Meaning | Example |
|---|---|---|
l (list) | Arguments are passed one by one, ending with |
|
v (vector) | Arguments are passed as an array ending with |
|
p (path) | Search the |
|
e (environment) | You pass the environment variables explicitly |
|
The full set in glibc: execl, execlp, execle, execv, execvp, execvpe (a GNU extension) and the system call execve. Note that the first argument after the path is argv[0], which by convention is the program's name.
What Survives exec()?
Kept after exec | Replaced or reset by exec |
|---|---|
PID and parent PID | Code, data, heap, stack (whole old program) |
Open file descriptors (unless marked close-on-exec) | Signal handlers (caught signals reset to default) |
Current working directory, user ID (unless the new program is set-user-ID) | Memory mappings and shared memory attachments |
Ignored signals stay ignored | The old program's unflushed stdio buffers (lost) |
The fact that open files survive exec is what makes shell redirection (>, <) and pipes (|) work, as we will see in a moment and in Inter-Process Communication.
wait(): Waiting for a Child
A parent uses wait() or waitpid() to:
block until a child terminates, and
collect the child's exit status (the number it passed to
exit()or returned frommain()).
wait(&status)waits for any child.waitpid(pid, &status, 0)waits for a specific child. With theWNOHANGoption, it returns immediately if the child has not finished yet.Both return -1 when the caller has no children left. That is why our puzzles use
while (wait(NULL) > 0);to wait for all children.
The status is decoded with macros: WIFEXITED(status) (did it exit normally?), WEXITSTATUS(status) (its exit code), WIFSIGNALED(status) and WTERMSIG(status) (was it killed by a signal, and which one?).
Putting It Together: How a Shell Runs a Command
Here is the core of every Unix shell, in about 30 lines:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
/* Run one command the way a shell does: fork + exec + wait */
static void run(char *const argv[]) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) { /* child: become the command */
execvp(argv[0], argv);
perror("execvp"); /* only runs if exec failed */
_exit(127);
}
int status; /* parent: wait for the child */
waitpid(pid, &status, 0);
if (WIFEXITED(status))
printf("[parent] child %d exited with status %d\n",
pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("[parent] child %d was killed by signal %d\n",
pid, WTERMSIG(status));
fflush(stdout);
}
int main(void) {
char *cmd1[] = {"ls", "-l", "/etc/hostname", NULL};
char *cmd2[] = {"ls", "/no/such/file", NULL};
char *cmd3[] = {"no_such_program", NULL};
run(cmd1);
run(cmd2);
run(cmd3);
return 0;
}
Output:
-rw-r--r-- 1 root root 6 Nov 2 08:11 /etc/hostname
[parent] child 19261 exited with status 0
ls: cannot access '/no/such/file': No such file or directory
[parent] child 19262 exited with status 2
execvp: No such file or directory
[parent] child 19263 exited with status 127
What happened for each command:
ls -l /etc/hostnamesucceeded: exit status 0.ls /no/such/fileran, butlsitself reported a problem: exit status 2 (seeman ls: 2 means serious trouble, such as being unable to access a file named on the command line).no_such_programcould not even be loaded, soexecvpreturned, and our child called_exit(127). 127 is the same code thatbashuses for "command not found".
The child calls _exit() instead of exit() after a failed exec. _exit() ends the process immediately, without flushing stdio buffers that were copied from the parent (remember the buffered-output trap).
Why Separate fork() and exec()?
Why not one call that creates a process running a new program (like Windows' CreateProcess())? Because the gap between fork and exec is extremely useful. In the child, before calling exec, the shell can:
redirect output: open a file and make it stdout (this is how
ls > files.txtworks),connect a pipe to stdin or stdout (this is how
ls | wc -lworks),change directory, drop privileges, set resource limits, change environment variables.
The new program inherits all of this without knowing anything about it. This simple design is one of the main ideas of Unix.
Zombie Processes
When a child terminates, the kernel cannot delete it completely, because the parent may still want its exit status. So the kernel frees the child's memory and other resources but keeps a small entry (its PID, exit status and resource usage) in the process table. A process in this state is a zombie.
A zombie process is a process that has finished execution but still has an entry in the process table, because its parent has not yet collected its exit status with wait().
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) {
printf("Child %d: exiting now\n", getpid());
exit(7);
}
sleep(1); /* child is dead, but parent has NOT called wait() yet */
char cmd[64];
snprintf(cmd, sizeof cmd, "ps -o pid,ppid,stat,cmd -p %d", pid);
printf("--- before wait() ---\n");
fflush(stdout);
system(cmd);
int status;
waitpid(pid, &status, 0); /* reap the zombie */
printf("--- after wait(): exit status = %d ---\n", WEXITSTATUS(status));
fflush(stdout);
system(cmd);
return 0;
}
Output:
Child 15060: exiting now
--- before wait() ---
PID PPID STAT CMD
15060 15059 Z+ [zombie] <defunct>
--- after wait(): exit status = 7 ---
PID PPID STAT CMD
Before wait(), ps shows the child with state Z and the label <defunct>. After wait() collects the status (7), the entry disappears completely, so ps prints only its header. This collection is called reaping the child.
A few zombies are harmless and short-lived. But a long-running parent that never calls wait() keeps piling them up. Each one holds a PID, and if the system runs out of PIDs, no new processes can be created. The fix is to always wait for your children (or handle SIGCHLD). You cannot kill a zombie, because it is already dead; you must make the parent reap it, or kill the parent.
Orphan Processes
The opposite situation: the parent exits while the child is still running. The child becomes an orphan.
An orphan process is a running process whose parent has terminated. The kernel re-parents it to another process (traditionally init, PID 1), which will later reap it.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) {
printf("Child : my parent is %d\n", getppid());
sleep(2); /* parent dies meanwhile */
printf("Child : now my parent is %d\n", getppid());
return 0;
}
printf("Parent %d: exiting without waiting\n", getpid());
return 0;
}
Output:
Parent 19306: exiting without waiting
Child : my parent is 19306
Child : now my parent is 19296
The child's parent changed from 19306 to 19296 while it was sleeping. Classic textbooks say the orphan is adopted by init (PID 1), and that is what happens on many systems. On modern Linux, a process can mark itself as a child subreaper (using prctl(PR_SET_CHILD_SUBREAPER)), and orphans are then adopted by the nearest subreaper ancestor instead. systemd --user and container init processes do this, and in this run (WSL2) the session's /init process adopted the orphan. Either way, the new parent will reap the orphan when it ends, so orphans do not become permanent zombies.
Zombie | Orphan |
|---|---|
Child is dead, parent is alive but has not called wait() | Child is alive, parent is dead |
Uses only a process-table entry and a PID | Uses normal resources; it is a normal running process |
Shown with state Z / <defunct> | Shown with a new PPID (1 or a subreaper) |
Fixed by the parent calling wait() | Handled automatically by re-parenting |
Other Ways to Create Processes
vfork(): an old optimisation where the child borrows the parent's memory (no copy at all) and the parent is suspended until the child calls exec or
_exit. With copy-on-write, plain fork is usually fast enough, and vfork is easy to misuse.posix_spawn(): a standard library function that does "fork + exec" in one call, with options for redirecting file descriptors. Many language runtimes use it to start child processes.
clone(): Linux's flexible system call that lets the caller choose exactly what the child shares with the parent (memory, open files, signal handlers...). Both
fork()and thread creation are built on it, as we will see in Threads & Multithreading.CreateProcess(): on Windows, one call creates a new process and loads the given program into it. There is no fork-style copy.
Common Mistakes
Assuming the child runs first (or the parent runs first). The order is up to the scheduler. Use
wait()or other synchronization if order matters.Expecting a variable changed in the child to change in the parent. After fork, they have separate memory. To share data you need IPC (next chapters).
Writing code after exec as if it always runs. Code after a successful exec never runs. Code after exec is only for handling a failure.
Forgetting the NULL at the end of exec's argument list. exec has no other way to know where the list ends.
Forgetting argv[0]. In
execlp("ls", "ls", "-l", (char *)NULL), the first "ls" is the program to find and the second "ls" isargv[0].Not calling wait(). This creates zombies in long-running programs.
Not flushing stdout before fork(), which can print things twice.
Interview Questions
What does fork() return?
0 in the child, the child's PID (a positive number) in the parent, and -1 in the parent if the fork failed.
How many processes are created by n consecutive fork() calls?
There are 2n processes in total, so 2n − 1 new child processes.
What is the difference between fork() and exec()?
fork() creates a new process that is a copy of the caller. exec() does not create a process; it replaces the program running inside the current process, keeping the same PID.
What is copy-on-write?
An optimisation where, after fork, parent and child share the same physical pages marked read-only. A page is copied only when one of them writes to it, so fork is fast and memory is not wasted.
What is a zombie process? How do you remove it?
A process that has terminated but whose parent has not yet called wait() to read its exit status. It holds only a process-table entry. It is removed when the parent calls wait()/waitpid(), or when the parent dies and the zombie is adopted and reaped by init or a subreaper.
What is an orphan process?
A process whose parent has terminated while it is still running. The kernel re-parents it to init (PID 1) or to the nearest subreaper, which reaps it when it ends.
Does exec() change the PID?
No. exec replaces the program, not the process. The PID, parent PID and open file descriptors (unless close-on-exec) stay the same.
Why does Unix separate fork() and exec()?
So the child can adjust its environment (redirect files, set up pipes, change directory or user) between the two calls. The new program then inherits these settings without needing special code.
Summary
Processes form a tree; every process has a PID and a parent PID.
fork()creates a child that is a copy of the parent. It returns 0 in the child and the child's PID in the parent.After fork, parent and child have separate memory (implemented efficiently with copy-on-write) and run in an unpredictable order.
n consecutive forks produce 2n processes.
exec()replaces the current program with a new one; the PID stays the same and exec never returns on success.wait()/waitpid()let the parent wait for a child and read its exit status.A shell runs a command with fork → exec (in child) → wait (in parent).
A zombie is a dead child not yet reaped; an orphan is a living child whose parent died.
fork() copies, exec() replaces, wait() collects.