Search code examples
cfork

What happens when fork() in a condition?


Can anyone give me the output(with an explanation) of this code? Thank you...

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

int main() 
{ 
    if (fork() && (!fork())) { 
        if (fork() || fork()) {
            fork(); 
        } 
    } 
    printf("Friend\n");
    return 0; 
}

Solution

  • Before go into the code it is better to understand the what is fork() system call

    fork() system call creates a new process by the 'parent' and the newly created process called as 'child' process

    child process is returns 0 and parent returns positive integer when fork is sucess

    That's the clue here

    So all two process work concurrently from that program counter onwards...

    in here fork() is in the if condition and it is bit tricky as well when guessing the output

    1. first fork() creates new C1 -> 0

    2. second fork() creates new C2 -> !0 -> 1

    so first condition is statisfied by C2 (which parent positive integer and c2's 0) but not statified by either parent or child C1 so other forks are not going to work

    then C2 go into the other if condition and maked another two forks

                C2
              /    \
             C2     C3
           /   \   /  \
          C2   c4  c3  c5
    

    Then all created processes (including parent) prints the "Friend" output 7 times