Animated Example #1

Listen to me!

In this program, the parent and child process are mimicking an argument between an imaginary parent yelling "listen to me!" and an imaginary child yelling "No way!". Try to hand trace the output of this code by drawing a fork diagram, keeping track of each process and their function calls. 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

Listen to me!
No way!
Listen to me!
No way!
Listen to me!
No way!
I give up...
Whatever.

The answer above is only one of the possible answers for this problem. Since the two processes are happening simultaneously, the "Listen to me" and "No way!" statements could be printed in any order. Your answer should specify, however, that the "Listen to me" and "No way" statements are printed before the "Whatever." and "I give up..." statements since they are outside of the for-loops.

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 i: