Animated Example #4

A Simple Wait

Notice the effect of the waitpid() call on the parent process: after the parent calls waitpid(), it "waits" for the child process to terminate before it continues to execute the subsequent lines of code. Read more about the waitpid() function at the Linux Man Page. 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

I'm the child!
I'm the parent, and I'm done waiting!

The output for this program is fixed. This means that the order of the output does not change from one run to another because waitpid() essentially adds "order" to the printf() statements.

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 how the waitpid() call affects the parent process: