Animated Example #6

The Sleepy Program

Try to hand trace the output of this code by drawing a fork diagram that keeps track of each process' sleep() calls and printf() statements. Read more about the sleep() function at the Linux Man Page. Assume that if you remove all sleep() calls, the program would finish almost instantaneously (under 0.01 seconds). 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

1
3
5
7

The output for this program is fixed. This means that the order of the output does not change from one run to another because the sleep() calls add "order" to the program.

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 effect of each sleep() call on each process, the printf() statements, and the sleep "countdown" located on the left of each process to help you see the process execute in real time: