If a program calls fork() three times in a row, how many processes run in total?
Each unconditional fork() doubles the number of processes, so n sequential calls give 2^n processes in total: 8 for three calls, meaning 7 new children plus the original.
Explain it simply
Picture cell division. One cell becomes two, each of those becomes four, each of those eight. Every process that reaches a fork() line splits into two, and both halves continue to the next line.
For n unconditional forks, total processes = 2^n, and new processes created = 2^n - 1.
Example
fork(); // line 1
fork(); // line 2
fork(); // line 3
printf("Hi\n");Count by line:
- Before line 1: 1 process
- After line 1: 2 processes
- After line 2: 4 processes
- After line 3: 8 processes
All 8 reach the printf, so "Hi" is printed 8 times, and 7 children were created.
If the forks are guarded, the count changes. In if (fork() == 0) fork(); only the child forks again, so you get 3 processes, not 4: the original, its child, and the child's child.
What to say in the interview
"Each unconditional fork doubles the process count, so three forks give 2^3 = 8 processes and 7 new ones. The trick is to check whether later forks run in both parent and child. If a fork sits inside an if on the return value, only one side forks."
Common mistakes
- Answering 3 or 6 by adding instead of doubling.
- Forgetting the original process when counting.