1,117 views
A process executes the following segment of code:

int main() {

fork();

fork() && fork();
}

The number of new processes created is __________

Can someone pls explain me the solution

Yes your ans. is correct but how did you solve ?
Can you please write a much better explanation.
reshown by
First thing to keep in mind is a child process is returned 0  if it is created successfully. It return a +ve value to parent . Now,after the first fork() .Parent P first child C1 will be created. Now, after 2nd fork() parent P and C1 make again 2 children let them be C2 and C3 respectively. Now, C2 will return +ve value to P .So,Child C2 don;t continue further as && condition become false(returned 0). But Parent P will go on to 3rd fork(). It will create another child let it be C4.

Now,coming to C1 , now C3 will return +ve value to it's parent which is C1,So,c3 will stop here (0 is returned to child). Now,C1 will execute further and split into new child C5.

So,now there are no more forks .So, 5 child were created.
Your statements are contradicting with the ones I have written in my notes.

Anyway thanks.

Let's see if someone else reply too for this.
what will be ans ?

what fork() && fork() will check?

Will it check "if" condition?

@srestha Ma'am please help us in getting a clear and accurate explanation for this problem.

Thanks.

yes i'm also getting 5.

number the forks: 1.fork()

2.fork() && 3.fork()

let's say there is process P. P-parent process, C child process

1.fork(): P,C

2.fork(): P,C1,C,C2 out of these processes, process id of P and C are non-zero and process id of C1 and C2 are 0.

C1 is the child process created after forking P. C2 is the child process after forking C.

3.fork():{only P and C will execute, as only their process id's are non-zero} P,C3,C,C4

C3 is the child process created after forking P. C4 is the child process created after forking C

finally count the number of child processes created, which is equal to 5.

5 child process be there

Look ans needs to be 6

We also need to include the parent process, as it get created after running the code.

at first we have  to learn how the && is executed.

exp=exp1&&exp2

case1

exp1==0 then exp2 will not be executed and overall value of the exp=0

case2

exp2!=0 then exp2 will be executed and overall value will be depends on the value of exp2.

Now here fork() returns pid of child process to parent process which is not equal to 0 and 0 to the child process

In below diagram I have explained how the code is executed.So the number of new processes will be 5.

1 vote