Reputation: 308
There are multiple questions about fork() on SO and I have been reading them for quite a while. I am trying to solve this trick question which states like this:
Consider the code fragment:
if(fork==0)
{a = a+5; printf("%d, %d \n", a, &a);}
else{a = a-5; printf("%d, %d \n", a, &a);}
Let u, v be the values printed by the parent process and x, y be the values printed by the child process. Which of the following is true:
a) u = x+10 and v = y
b) u = x+10 and v != y
c) u+10 = x and v = y
d) u+10 = x and v != y
Obviously, the addresses of parent and child process are different so the answer has to be either b or d. I am not able to interpret even how u
can be x+10
or u+10
can be x
. How exactly does this work? fork()
creates two exact copies of the processes. If the fork()
returns zero, it means the parent is executing in the if
block. Otherwise, the child executes the statement in the else
block and then the parent executes in the if
block? Is my line of thought correct?
Upvotes: 0
Views: 49
Reputation: 798506
Is my line of thought correct?
Almost.
fork()
creates two exact copies of the processes.
Obviously, the addresses of parent and child process are different
These two statements contradict. There is no "reloading" of the process after the fork, therefore all addresses must be the same. This is possible due to the MMU of the CPU creating a distinct virtual address space for each process, and is one of the primary reasons why the kernel must be heavily modified in order to run on a CPU without one.
If the
fork()
returns zero, it means the parent is executing in theif
block.
fork()
returns the new child's PID in the parent, and 0 in the child.
Upvotes: 2