CS FundamentalsHardGATE CS (PYQ pattern)

Assume every fork() succeeds and output is unbuffered. int main(void) { int i; for (i = 0; i < 3; i++) { if (fork() == 0 && fork() == 0) continue; break; } printf("%d\n", i); return 0; } How many lines are printed, and what is the sum of the printed values?

  1. A. 7 lines, sum 12
  2. B. 7 lines, sum 9
  3. C. 15 lines, sum 9
  4. D. 6 lines, sum 6

Correct answer: B. 7 lines, sum 9

In each iteration the current process P forks a child C; P sees a non-zero value, the && short-circuits and P breaks. C forks G; C sees non-zero and breaks, G sees 0 and continues to the next iteration. So iterations 0, 1, 2 each leave two processes printing that i (0, 0, 1, 1, 2, 2), and the last G leaves the loop with i = 3. 7 lines, sum 9.

More Operating Systems questions

Exams that ask this topic