COMS 3157 Advanced Programming

Fork Diagrams

Forking processes can get confusing pretty quickly, but fork diagrams are a really good way to keep track of the relationships between all the different running processes.

Example

Let’s take a simple true/false question that appeared on a past AP midterm:

True or False: The value of the expression (fork() == fork()) is always 0.

This expression calls fork() on both sides of the == comparison. fork() will be called twice (once on the LHS and once on the RHS). Each call is going to create a child and a parent. This will create a total of four processes, each of which compares the two values that the calls to fork() returned.

Note that fork() returns 0 in the child process and returns the pid of the child in the parent process.

Diagramming the Forking Processes

Let’s assume that the PIDs we’re dealing with are 2000, 2001, 2002, and 2003 (it doesn’t really matter which numbers we choose).

                        first fork           second fork
original(pid=2000)______parent(pid=2000)_____parent(pid=2000) 
                  \                     \____child(pid=2002)
                   \
                    \___child(pid=2001) _____parent(pid=2001)
                                        \____child(pid=2003)

The diagram above is a great way to draw the forking process. Time goes from left to right, and existing processes keep their positions as time progresses.

Explanation

Solution

Therefore, the answer is false, because in the final case where we compare the child process of both forks, we have 0 == 0, which evaluates to 1, and as such the expression fork() == fork() will not always evaluate to 0.

This guide was originally written by Emma, a former AP TA.