← 🧵 Processes, Threads & System Calls
Subtopic 4 of 4

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

  1. Draw the original process as a node.
  2. At each fork, add a child that continues after that fork with the same variable values.
  3. For if (fork() == 0): only the child enters the branch.
  4. 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(); fork(); fork(); printf("x");
Total processes (incl. the original)8
Times printf runs8
New child processes7
P0 (original)
└ P1 (child of P0)
└ P4 (child of P1)
└ P7 (child of P4)
└ P5 (child of P1)
└ P2 (child of P0)
└ P6 (child of P2)
└ P3 (child of P0)

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();

Remember: n sequential forks: 2ⁿ processes. Child continues after the fork. Conditions like == 0 or && limit who forks.
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.