in Operating System edited by
1,118 views
0 votes
0 votes
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
in Operating System edited by
1.1k views

9 Comments

Is answer 5?
0
0
Yes your ans. is correct but how did you solve ?
0
0
Can you please write a much better explanation.
0
0
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.
0
0
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.
0
0
what will be ans ?

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

Will it check "if" condition?
0
0

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

0
0
0
0
Thanks.
0
0

2 Answers

0 votes
0 votes
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.

2 Comments

5 child process be there

 

0
0

Look ans needs to be 6

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

 

0
0
0 votes
0 votes

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.

Related questions

3 votes
3 votes
1 answer
2