858 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

109
views
1 answers
1 votes
vivek10010 asked Jun 23
109 views
How many child processes will be created in the following code: main(){if(!fork()){ if(!fork()) fork();}fork();}
441
views
1 answers
2 votes
Sparkboy asked Apr 4
441 views
Consider the following pieces of codes for fork( ) system call. Solve and explain how many child processes are created upon execution of this program? Snippet 1: ... 0; }Learning Outcomes. Understand the working of fork ( ) system call.
1.2k
views
4 answers
2 votes
Philosophical_Virus asked Dec 10, 2023
1,186 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
866
views
1 answers
0 votes
Erwin Smith asked Apr 11, 2023
866 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 possible?2,4,1,701,7041,2,4,704,7012,704,4,701,11,704,2,4,701