Animated Example #3

Fork()==Fork()

This is a tricky program that requires you to trace the return values of each fork() call depending on which process it was called in. Therefore, tracing the output of the program will require you to draw an accurate fork diagram. 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

fork() == fork() is false
fork() == fork() is false
fork() == fork() is false
fork() == fork() is true
Since these 4 statements are being printed simultaneously, the printing order can change from one run to another.

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 and the printf() statements.
The four comparisons that are being done are: fork() = 1001 with fork() = 1002, fork() = 1001 with fork() = 0, fork() = 0 with fork() = 1003, and fork() = 0 with fork() = 0. This is why there is only one printf() statement that indicates that fork() == fork() is true.