CS FundamentalsVery hardGATE CS (PYQ pattern)

Assume every fork() succeeds and each printf output is flushed immediately. int main(void) { for (int i = 0; i < 4; i++) { if (fork() == 0) printf("A"); else if (i % 2 == 1) { printf("B"); break; } } printf("C"); return 0; } How many characters are printed in total over all processes?

  1. A. 32
  2. B. 29
  3. C. 25
  4. D. 21

Correct answer: C. 25

Let f(j) be the characters output by a process entering the loop at index j: f(4) = 1; f(j) = (1 + f(j+1)) for the child plus either 2 (B and C, parent breaks, j odd) or f(j+1) (parent continues, j even). f(3) = 4, f(2) = 9, f(1) = 12, f(0) = 25.

More Operating Systems questions

Exams that ask this topic