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.
Let’s take a simple true/false question that appeared on a past AP midterm:
True or False: The value of the expression (
fork()) is always 0.
This expression calls
fork() on both sides of the == comparison.
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() returns 0 in the child process and returns the pid of the
child in the parent process.
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.
The process that was the parent both times (
pid=2000) will have seen
return 2001 the first time, then 2002 the second time, as these are the PIDs of
its children. 2001 != 2002.
The process that was first the parent, but later the child (
fork() return 2001 the first time, but 0 the second time.
2001 != 0.
The process that was first the child, but later the parent (
fork() return 0 the first time, but 2003 the second time.
0 != 2003.
The process that was the child both times (
pid=2003) will have seen
return 0 the first time, then 0 again the second time. 0 == 0, and the value of
this expression is 1.
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.