harshit
harshit

Reputation: 1

fork() and Binary tree creation

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

Answers (1)

Sorter
Sorter

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;
}
  • There are 5 fork calls(A,B,C,D,E).
  • The program starts with a main thread(m).
  • When fork is executed a new child process will be created. (c)

So according to the diagram shown, each node will ALWAYS have 2 childs nodes.

  • The left node is always the creating process(m)
  • right node is the child process.

“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()

enter image description here

Upvotes: 1

Related Questions