The fork function opens a child process with a copy of the variables values of the parent process. In this example the else
will be executed for the child process and x
will go to 4. In the parent it will go to 1.
EDIT:
It happens that the fork when executed opens a second process and both processes execute the next line that is just after the original fork with this we have the following:
It happens the first fork
in if
where an assignment is made to the pid
variable. The result of this is 0 that in the test condition is ok and enters the block. The first line of this block is a fork
that assigns nothing to pid
, so we have a child process that does not enters the else
and starts executing on the next line which is another fork
assigning pid
. But then the parent process of that second child also executes fork
by assigning pid
. As one of these is the parent will assign 0 to pid
while the other does not decrease the x
variable.
With this we have:
pid = 45750x = 2 child of a fork inside if
pid = 45751x = 2 child of a fork of the other child inside the if
pid = 0x = 1 original parent
pid = 0x = 1 child of the original and parent of the second fork inside the if
In the child process of the original it enters else
which makes x=x+2;
that prints pid=45748x=4
.