Visually what happens to fork() in a For Loop

Here’s how to understand it, starting at the for loop.

  1. Loop starts in parent, i == 0

  2. Parent fork()s, creating child 1.

  3. You now have two processes. Both print i=0.

  4. Loop restarts in both processes, now i == 1.

  5. Parent and child 1 fork(), creating children 2 and 3.

  6. You now have four processes. All four print i=1.

  7. Loop restarts in all four processes, now i == 2.

  8. Parent and children 1 through 3 all fork(), creating children 4 through 7.

  9. You now have eight processes. All eight print i=2.

  10. Loop restarts in all eight processes, now i == 3.

  11. Loop terminates in all eight processes, as i < 3 is no longer true.

  12. All eight processes print hi.

  13. All eight processes terminate.

So you get 0 printed two times, 1 printed four times, 2 printed 8 times, and hi printed 8 times.

Leave a Comment