Draw a process tree for this code int main int x 0 int y
Draw a process tree for this code.
int main() {
int x = 0;
int y = 0;
... ...
x = fork();
y = fork();
if( x == y)
fork();
... ...
}
Solution
int main() {
int x = 0;
int y = 0;
... ...
x = fork();
y = fork();
if( x == y)
fork();
... ...
}
fork()-A
fork()-B
fork()-C
At level 0,we have only main process.The main will create child c1 and both will continue execution.The children are numbered in increasing order of their creation.
At level 1, we have m and C1 running, and ready to execute fork() – B. (Note that B, C and D named as operands of && and || operators). The initial expression B will be executed in every children and parent process running at this level.
At level 2, due to fork() – B executed by m and C1, we have m and C1 as parents and, C2 and C3 as children.
The return value of fork() – B is non-zero in parent, and zero in child. Since the first operator is &&, because of zero return value, the children C2 and C3 will not execute next expression (fork()- C). Parents processes m and C1 will continue with fork() – C. The children C2 and C3 will directly execute fork() – D, to evaluate value of logical OR operation.
