1.4fork() and process trees
The idea
fork() creates a child that is a copy of the caller. It returns 0 to the child and the child's pid to the parent, and both continue from the statement after the fork.
Think of it like this: Photocopying a half-written form: both copies continue from the same line, but you can tell them apart by the number the copier gives you.
Why it exists
It is how Unix starts every program (fork then exec), and it is a favourite counting puzzle: how many processes, how many prints.
How it works
- Draw the original process as a node.
- At each fork, add a child that continues after that fork with the same variable values.
- For
if (fork() == 0): only the child enters the branch. - Count nodes for processes, and count how many nodes reach each print.
Worked example: fork(); fork(); fork(); printf("x");
Each fork doubles the number of processes: 1 → 2 → 4 → 8. All 8 reach the printf, so 8 prints and 7 children.
Now play with it
- →Switch the program to fork() && fork(): only the parent runs the second fork, so 3 processes.
- →Try for loop of 3 forks: also 8, because children keep looping with the current counter.
fork() returns 0 in the child and the child's pid (non-zero) in the parent, and the child continues from the statement after the fork. n unconditional forks in a row give 2ⁿ processes, so 2ⁿ − 1 children. Output order is not fixed, only the counts are.
Check yourself
How many processes (including the original) after: fork(); fork(); if (fork() == 0) fork();
Exam notes (the dense version)
fork() creates a copy of the calling process. It returns 0 in the child and the child's pid (non-zero) in the parent, and both continue from the next statement. n unconditional forks in a row give 2ⁿ processes in total (2ⁿ − 1 children). In if (fork() == 0) only the child enters the branch; with && and || the second fork runs only in the parent or only in the child respectively. wait() makes the parent block until a child exits; a child whose parent has not waited is a zombie.
Previous year questions: Processes, Threads & System Calls (15)
PYQs are grouped by topic, so this is the full set for Processes, Threads & System Calls; try the ones that match this subtopic. Open all 15 on the topic page.