Viking inside if a dilemma

What happens if I call:

if (fork() == fork())
   //do something

      

Do both parents and both children enter an expression or what procedure in this case?

+3


source to share


2 answers


With two pitchforks, you get four processes: one parent, two children, and one grandchild.

The order in which the two forks occur is undefined, since C does not require an expression to evaluate from left to right. In the end, it doesn't matter what happens first, so let's pretend the left one fork()

happens first. When this happens, you will have one parent and one child. The parent will receive the child PID and the child will receive 0

.

Call the parent A

and child B

. This is what these two processes look like after doing a left fork:

A          if (<pidof B> == fork())
|
+--B       if (0 == fork())

      



Now each of them will execute the correct fork. The two processes become four. Let's call the B

new child C

and A

new child D

. Again, each call fork()

returns one of two values: the new child PID in the parent process, or 0 in the child process. Then our four processes are:

A          if (<pidof B> == <pidof D>)
|
+--B       if (0 == <pidof C>)
|  |
|  +--C    if (0 == 0)
|
+--D       if (<pidof B> == 0)

      

Once this happens, the process C

will be the only one that passed the test if

.

+6


source


Try this experiment:

#include<stdio.h>
#include <unistd.h>

int main(void)
{
  printf("beginning\n");

  if(fork() == fork())
    {
      printf("two are equal\n");
    }

  printf("done\n");

  return 0;
}

      



One process prints "start", four prints "done", and one print "two are equal". Is this all clear?

+1


source







All Articles