Garrick
Garrick

Reputation: 689

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 .

Upvotes: 4

Views: 15868

Answers (2)

Alexey Guseynov
Alexey Guseynov

Reputation: 5304

For first block:

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

Child process receives 0 and skips the if, and the parent proceeds to calculate condition. Parent executes next fork and enters the if block where it forks again. So we have 3 fork invocations resulting in 4 processes.

Then every of these 4 processes executes next block. Let's look at a single one:

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

We fork once. The child receives non 0 and condition result is already true, so it enters the if without evaluating second part of the condition and forks there. So we have 2 fork invocations already. Parent process has to evaluate second fork in the expression and it's child enters the if and forks again. So 2 more fork invocations. Total 4 calls which result in 5 running processes.

So each of 4 processes from first block forks in-to 5 processes in second block resulting in total of 4*5 = 20 processes. And each one prints "hello".

Upvotes: 3

amaneureka
amaneureka

Reputation: 1150

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".

Upvotes: 5

Related Questions