CS FundamentalsHardGATE CS (PYQ pattern)

Assume every fork() succeeds and output is not lost or duplicated. int x = 1; int main(void) { int *p = &x; if (fork() == 0) { *p += 2; if (fork() == 0) x *= 3; } else { wait(NULL); x += 10; } printf("%d ", x); return 0; } What is the sum of all the numbers printed?

  1. A. 23
  2. B. 37
  3. C. 14
  4. D. 29

Correct answer: A. 23

Each process has its own copy of x (p points into the caller's own copy). The child makes x = 3 and prints 3; its child (the grandchild) inherits 3, makes 9 and prints 9; the original parent still has x = 1 and prints 11 after waiting. Sum = 3 + 9 + 11 = 23. Treating x as shared memory gives values like 9, 9, 19 (37); forgetting the grandchild gives 14.

More Operating Systems questions

Exams that ask this topic