Reputation: 1
How binary tree will be created for following code ?
#include <stdio.h>
#include <unistd.h>
int main()
{
fork();
fork() && fork() || fork();
fork();
printf("forked\n");
return 0;
}
Basically i am not able to solve logical operator conditions .For unconditional fork() statements it can easily be done but what about above code . For reference here is the link http://www.geeksforgeeks.org/fork-and-binary-tree/
Upvotes: 1
Views: 1112
Reputation: 10220
#include <stdio.h>
int main()
{
fork(); /* A */
( fork() /* B */ &&
fork() /* C */ ) || /* B and C are grouped according to precedence */
fork(); /* D */
fork(); /* E */
printf("forked\n");
return 0;
}
So according to the diagram shown, each node will ALWAYS have 2 childs nodes.
“On success, the PID of the child process is returned in the parent, and 0 is returned in the child.”
Lets look at fork B. the parent process(m) will return a non-negetive pid and child process(c1) returns 0.
Therefore, the parent process executes fork C, but skips fork D due to short circuit evaluation.
(1234 && 4392) || fork()
The newly created child process skips fork C and executes fork D for above mentioned reason.
(0 && fork() ) || fork()
Upvotes: 1