cif-statementprocessforksimultaneous-calls

if else statement concurrency with fork()


While reading through some articles about fork() in C, I saw this example (code below) which I couldn't understand:

Understanding problem: We only run "if" or "else" and not both. But since the child and parent processes run "simultaneoustly", in this example we see that we went through "if" and "else" both! Eventhough it's similtaneous, it isn't in reality, it depends on which one of the processes will get the CPU first (right?).

What makes everything "weirder" is that we might first go through the "else" and then through the "if". How is this possible ?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
    // child process because return value zero
    if (fork() == 0)
        printf("Hello from Child!\n");
  
    // parent process because return value non-zero.
    else
        printf("Hello from Parent!\n");
}
int main()
{
    forkexample();
    return 0;
}

Possible Outputs are:

Hello from Child!

Hello from Parent!

(or)

Hello from Parent!

Hello from Child!


Solution

  • Remember that the fork function actually returns twice: once to the parent with the child's pid and once to the child with 0.

    At that point you have two independent processes running the same code and printing to the same terminal. And since you have two processes, the kernel is free to schedule them in any way it sees fit, meaning the output of either process can appear in any order.