Sub topic 5
Creating and Ending Processes with fork, exec, and wait
This chapter assumes you know what a process is, how a PCB records its state, and how a system call moves from user mode into the kernel. It also assumes basic C. You will learn how Unix-like systems create a process, how a new program replaces the old one, how a parent collects a child's result, and how to count the processes and output lines in GATE-style fork questions.
The Three Calls and Their Roles
Unix separates "make a new process" from "run a new program". Three system calls cooperate:
| Call | What it does | Returns |
|---|---|---|
| `fork()` | Creates a child that is a copy of the caller | Twice: child PID to the parent, 0 to the child, -1 on error |
| `exec` family | Replaces the current program image with another program | Only on failure (-1) |
| `wait` / `waitpid` | Blocks the parent until a child terminates, then returns its status | Child PID, or -1 on error |
The key point: fork creates a new process, but exec does not. exec keeps the same process (same PID) and swaps its code, data, heap, and stack for those of a new program.
What fork Copies
After fork, the child has its own PCB and its own PID. It receives a copy of the parent's address space, open file descriptors, and current program counter. Both processes continue from the instruction right after fork.
- The child's PPID (parent PID) is the parent's PID.
- Variables are copied. A change in one process is not visible in the other.
- Open file descriptors are duplicated, but they refer to the same open file entries. The two processes share the file offset.
- Real systems use copy-on-write. Pages are shared read-only until either process writes to one. Then the kernel copies only that page. This makes
forkcheap, and it makesforkfollowed byexeccheap.
The only difference the program can see right away is the return value. That is how code tells the two processes apart.
A Complete Example
The program below forks, runs echo in the child, and reads the exit status in the parent.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
execlp("echo", "echo", "hello from the child", (char *)NULL);
perror("execlp");
_exit(127);
}
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("child exited with status %d\n", WEXITSTATUS(status));
}
return 0;
}Points to notice:
- The three-way test on
pidis the standard pattern: negative means failure, zero means "I am the child", positive means "I am the parent". - Any code after
execlpruns only ifexecfailed. That is why the child callsperrorand_exit(127). _exitis used instead ofexitin the child after a failedexec. It skips flushing buffered stdio data that the child inherited from the parent, which would otherwise be written twice.- The
WIFEXITEDandWEXITSTATUSmacros decode the packedstatusinteger. Do not read the exit code fromstatusdirectly.
The output is:
hello from the child
child exited with status 0The order is guaranteed here only because the parent waits before it prints.
The exec Family
The letters after exec describe the argument style.
| Variant | Arguments | Searches PATH? |
|---|---|---|
| `execl` | List of strings | No |
| `execlp` | List of strings | Yes |
| `execv` | Array of strings | No |
| `execvp` | Array of strings | Yes |
| `execve` | Array plus environment array | No (this is the actual system call) |
The argument list must end with a null pointer. By convention the first argument is the program name.
On success, exec never returns, because the code that called it no longer exists. The PID stays the same. Open file descriptors stay open unless marked close-on-exec. This is how a shell redirects output: it forks, rearranges descriptors in the child, then calls exec.
Terminating a Process
A process ends in one of these ways:
- It returns from
mainor callsexit(status). - It calls
_exit(status)directly. - A signal kills it, for example a segmentation fault or
kill. - A parent kills it explicitly.
On termination, the kernel frees the memory and closes the files. It keeps a small record, the exit status, in the PCB until the parent asks for it.
Zombies and Orphans
These two states cause common confusion.
- A zombie is a process that has terminated but whose parent has not yet called
wait. It holds only a PCB entry. It cannot be killed, because it is already dead. It disappears when the parent waits. A parent that never waits and never exits leaks PCB entries. - An orphan is a process whose parent terminated first. The init process (PID 1) or a designated subreaper adopts it. Init calls
waitregularly, so orphans do not stay zombies once they finish.
Waiting Details
wait(&status) blocks until any child terminates. waitpid(pid, &status, options) waits for a specific child, and WNOHANG makes it return immediately if no child has finished. If the parent has no children, wait returns -1 at once. Calling wait also lets the kernel reclaim the zombie.
Counting Processes in fork Problems
GATE questions often put several fork calls in a row and ask how many processes exist or how many lines print. The rule: each fork doubles the number of processes that reach it, because both parent and child continue.
#include <stdio.h>
#include <unistd.h>
int main(void) {
fork();
fork();
fork();
printf("hello\n");
return 0;
}With n unconditional forks in sequence, the total is 2^n processes. Here n = 3, so hello prints 8 times. One of those 8 is the original process, so the number of newly created processes is 2^n - 1 = 7.
Variations change the count:
- Forks inside a condition. In
if (fork() == 0) fork();, only the child forks again. Total: 3 processes. - Forks in a loop.
for (i = 0; i < n; i++) fork();creates 2^n processes. The loop variable is copied, so children continue the loop from their current value ofi. - Return value tests.
if (fork() && fork())is short-circuit evaluation. The firstforkcreates two processes. Only the parent sees a nonzero value, so only the parent runs the secondfork. Total: 3 processes. - Buffered output. If
printfhas no trailing newline and output goes to a pipe or file, the buffer is copied byfork. The text can then appear more than once.
A Systematic Method
- Start with one process.
- At each
fork, split every live process into a parent branch (returns nonzero) and a child branch (returns 0). - Follow conditions on the return value for each branch separately.
- Count the processes that reach each
printf.
Common Errors
- Calling
forkin a loop without a guard in the child, which creates a "fork bomb" of exponential growth. - Forgetting to check for a negative return from
fork. - Treating the child's variable changes as visible to the parent. Address spaces are separate.
- Using code after
execwithout handling failure. - Never calling
wait, which leaves zombies. - Assuming the parent or child runs first. The scheduler decides, so output order without
waitis not defined.
Process Creation Costs
Creating a process by fork copies the PCB and page tables, even with copy-on-write. Creating a thread is cheaper because the address space is shared. That comparison comes in the chapter on threads.
Exercise
A program runs fork(); fork(); printf("x"); and then every process returns from main. How many times is "x" printed, and how many processes are created in addition to the original?
Show answer
The first fork gives 2 processes. Each of them runs the second fork, giving 4. Each of the 4 reaches printf, so "x" prints 4 times (assuming the output is flushed). The number of additional processes is 4 - 1 = 3.
Exercise
In if (fork() == 0) { fork(); } printf("y");, how many times is "y" printed? Which process is a zombie if the original parent exits without calling wait while children are still running?
Show answer
The first fork creates a parent and a child. Only the child runs the second fork, which creates a grandchild. Three processes reach printf, so "y" prints 3 times. No process becomes a zombie because the parent exits. Children that outlive their parent become orphans and are adopted by init. A zombie arises only when a child finishes before its parent has called wait.