Search code examples
unixfork

Fork() in an IF statment in UNIX


What I understand about fork() is that once the child process created by it, it knows nothing about the code that was exsited before that point we reached "fork()". But in if statments with multiple fork() it seems like the child process is doing the argument calculation even though it came before it's fork() creator.

For example:

int main ()
{
if((fork())==(fork()))
   printf ("Hello.\n");

printf ("Bye.\n");
return 1;
}

There would be a sum of 4 process including the father. In the child process (I will call it d) that was created by another child process, the fork() that created our d process is the second fork() in the if statement.

Even though that the first fork() shouldn't be familiar to d, it is my understanding that d process calculates that 0==0 and print "Hello" (the output is correct for sure).I have two questions:

1.How is it that the d process even able to reach the first fork() in the if statement that came before the fork() that created this d process (the second one) ?

2.Why in that point that we are in the d process does the first fork() equals to 0 if it happens only in the child process that was created by this specific fork() (the father of d) ?


Solution

  • What I understand about fork() is that once the child process created in knows nothing about the code that was existed before that point we reached "fork()".

    The child is an exact replica of the parent, apart from the return value of fork(). This includes all run-time state, including the memory and the CPU registers. That's all the memory the processes have, so they "remember" the same things.

    Let's rewrite your program like this:

    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
        pid_t a = fork();
        pid_t b = fork();
        if (a == b)
            printf ("Hello.\n");
        printf ("Bye.\n");
        return 1;
    }
    

    After the forks, there are four processes, the original one has a != 0 && b != 0 (and a != b since its two children are distinct), two others have one of a and b zero, and the fourth has a == b == 0. The last one is the only one where a == b, so that one runs the conditional printf() call.