Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fork() will work here?

{ 
    if(fork() && fork()) 
    { 
        fork(); 
    } 

    if(fork() || fork()) 
    {
        fork();
    } 

    printf("hello"); 
    return 0; 
} 

I am not getting how fork() will behave here and how many times hello will be printed.
I just know that fork() && fork() will produce total 3 process for 1 parent and similarly, fork() || fork() will produce 3 process for 1 parent.

After the 1st if condition, 3 processes are created and only parent will enter the if block. Total 4 processes are now there. Now, how to proceed further, I am completely screwed with this?

If possible, please show a tree diagram .

like image 507
Garrick Avatar asked Sep 08 '25 09:09

Garrick


1 Answers

Tree visualization!

if(fork() && fork()) 
{ 
    fork(); 
}

First if block

Now we have 4 process running in system; P, C1, C2 and C3.

And Each will execute next if block.

if(fork() || fork()) 
{ 
    fork(); 
}

Second if block

In total we will have 4*5 = 20 process running in the system and each will print "Hello".

like image 98
amaneureka Avatar answered Sep 10 '25 07:09

amaneureka