804 views
3 votes
3 votes
Pls explain if possible with diagram,answer given is 20!!!

How many times “GATE 2017 IIT Roorkee” is printed by following program?
int main()
{ if(fork() && fork())
{
fork();
}
if(fork() || fork())
{
fork();
}
printf(“GATE 2017 IIT Roorkee”);
return 0;
}
(a) 20 (b) 19 (c) 18 (d) 17

1 Answer

1 votes
1 votes

Suppose we have a process m. In the first if block, by executing fork() we will have two processes m & c1.

Since pid of c1 is 0, it will not be executed. now parent process will further execute fork which will give m  & c2. Since m && c2 = 0 it will fail if condition and we will only left with m which will enter into if block and execute fork(), thus giving m and c3.

Now we have 4 processes namely m, c1, c2, c3. take c1 for example.

In the first fork(), it will split into c1 an c4. since c1 > 0, condition is true and it will enter in if block anf execute fork().

whereas c4 will continue executing conditional statement and call fork(). Now it has c4 and c6. since c6 is 0, if condition fails here and we will only left with c4 which call fork() and give c4 and c7.

In short c1 will give 5 processes. similarly m, c2, c3 will give 5 processes. So in total we will have 20 processes and each will print given statement.

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
863 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
0 votes
0 votes
1 answer
3
Erwin Smith asked Apr 11, 2023
777 views
void main() { int n = 1; if(fork()==0) { n = n<<1; printf(“%d, “, n); n = n <<1; } if(fork()==0) n=n+700; printf(“%d, “,n); }Which of the following output is not ...
0 votes
0 votes
1 answer
4
vikranty2j asked Mar 20, 2023
470 views
main(){int i,n; for(int i=0;i<n;i++){fork();printf("*");}}How many times ‘*’ will be printed? The answer is not 2^n ? why?