Animated Example #2

The Hardworking Child

Try to hand trace the output of this code by drawing a fork diagram that keeps track of each process' changing x values and printf() statements. Assume that the program is run with argv[1] = 3. When you're ready to check your answer, press the button below and watch the animation to see how I draw a fork diagram for this program.

Show Answer Hide Answer

2
2
4
2
2
4
4
8

Since these processes are running simultaneously, the printing order changes from one run to another. Your answer, however, should have the exact number of lines of output and the exact number of 2s, 4s, and 8s as the answer displayed above.

Now, click play to watch an animated visualization of this program. I choose to represent each process with a horizontal line, and each fork() call with a vertical line. Pay special attention to the return values of each fork() call, the printf() statements, and the changing values of the variable x: