The Fork function opens a child process with a copy of the values of the parent process variables. In this example the else
will be executed for the child process and x
will go to 4. Already at the father will go to 1.
EDIT:
It turns out that the executed Fork opens a second process and both processes run the next line that is just after the original Fork so we have the following:
Happens the first fork
in the if
where an assignment is made to the variable pid
. The result of this is 0 which in the test condition is ok and enters the block. The first line of this block is a fork
that attributes nothing to pid
, with that we have a child process that nay gets into the else
and starts running on the next line which is another fork
attributing to pid
. But soon after the father process of that second son also executes the fork
attributing to the pid
. As one of these is the father will assign 0 to pid
while the other does not decrease the variable x
.
With this we have:
pid=45750x=2 child of a Fork inside the if
pid=45751x=2 child of one other child Fork within the if
pid=0x=1 original parent
pid=0x=1 child of the original and parent of the second Fork within if
In the child process of the original else
that makes the x=x+2;
this prints pid=45748x=4
.
what I don’t understand is ,what is loaded for variables in the other 2 Fork()
– user48571
@user48571 You already executed the code to see the values of the variables?
– bfavaretto
on my machine returns Aki pid=45748x=4 pid=45750x=2 pid=45751x=2 pid=0x=1 pid=0x=1
– user48571
@user48571 Now with the output added more explanations
– prmottajr
when I make a call to Fork, what runs in the child process also includes a new Fork() in the child process?
– user48571
Yes because you only put the if testing the result in the first. In others made the call alone and they also work.
– prmottajr