fork() explorer
Step through fork() programs and predict their output.
fork() explorer
Predict, then step through — how many processes, and what do they print?
Puzzle 1 — one fork
int main(void) {
printf("A\n");
fork();
printf("B\n");
return 0;
}One process prints A.
fork() creates a child. Both parent and child continue at the next statement.
Both print B. Output: A B B (the two B's may appear in either order — the scheduler decides).
Puzzle 2 — forks in a loop
int main(void) {
for (int i = 0; i < 3; i++)
fork();
printf("hello\n");
return 0;
}1 process forks → 2 processes, both continue the loop with i = 1.
Each of the 2 forks → 4 processes.
Each of the 4 forks → 8 processes.
All 8 print hello. In general, n forks in sequence give 2n processes (2n − 1 new).
Puzzle 3 — using the return value
int main(void) {
int x = 10;
pid_t pid = fork();
if (pid == 0) { x = x + 5; printf("child x=%d\n", x); }
else { wait(NULL); x = x - 5; printf("parent x=%d\n", x); }
return 0;
}After fork() the child has its own copy of x = 10. Memory is not shared.
Child: pid == 0 → x = 15, prints child x=15.
Parent waits for the child, then x = 5 (its own copy!), prints parent x=5.
Changes in one process are invisible to the other. To share data, processes need IPC — Module 3.
How many processes exist after fork(); fork();?
In the child, fork() returns…
A child exits but the parent never calls wait(). The child is a…
The parent exits while the child is still running. The child becomes…