• edited by
14,530 views
12 12 votes

Consider the following code snippet:

if(fork()&& fork())
{
  fork();
    
}
if(fork()||fork())
{
  fork();
  fork();
    
}
printf("GATE 2017");


How many times GATE 2017 printed ?

3 Answers

Best answer
14 14 votes

// 1 process

if(fork() && fork())  //  creates 2 more  // After first fork() only parent one will execute 2nd fork().
{
fork();    // very first parent process will get here and creates one more process.
}

===== here total process = 4.  ( 1 is new process created by 1st fork and total 3 by parent process)


if(fork() || fork())    // creates 2 more by each 4 process. Here only new child by first fork() will execute 2nd fork.
{

// 2 process reach here (original plus 1st child that tried 2nd fork above) 
fork();   
fork();

// here tota = 8 process inside this "if" body.
}

total process here = 4 * ( 1 + 8) = 36.
printf("GATE 2017");

Ans = 36

Refer the following tree diagram => 

• selected by
3 3 votes
I Think 36 Times
• edited by
1 1 vote

if (fork() || fork()) ====>in the if loop second fork will not be executed if 1st fork value is not 0 and we have 4 process like that

if the first fork value is zero second fork will be executed 

• edited by
Answer:
Position:
Show:

Related questions

5 5 votes
2 2 answers
460
460 views
GO Classes asked Jul 15
460 views
Consider the following C program. Assume that every $\texttt{fork()}$ call succeeds.int main(void) { unsigned long int i; for (i = 0; i < 6; i++) if (fork() >= 0) continu...
3 3 votes
1 1 answer
313
313 views
GO Classes asked Jul 15
313 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int a = 0; int rc = fork(); a++; if (rc == 0) { rc = fork(); a++; } else { a++; } printf("a is %d\n", a); }...
4 4 votes
1 1 answer
310
310 views
GO Classes asked Jul 15
310 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int pid; pid = fork() && fork(); if (!pid) printf("A\n"); else printf("B\n"); return 0; }How many times are...
5 5 votes
1 1 answer
290
290 views
GO Classes asked Jul 15
290 views
Consider the following program. Assume that every $\texttt{fork()}$ call succeeds.int main() { int p1 = 1, p2 = 2, p3 = 3; p1 = fork(); if (p2 0) p2 = fork(); if (p1 0)...