CS FundamentalsVery hardGATE CS

How many numbers are printed in total, and what is their sum? (Every fork() succeeds; output unbuffered.)

How many numbers are printed in total, and what is their sum? (Every fork() succeeds; output unbuffered.)
int main() {
    for (int i = 0; i < 3; i++)
        if (fork() == 0)
            printf("%d ", i);
}
  1. A. 3 numbers, sum 3
  2. B. 7 numbers, sum 7
  3. C. 8 numbers, sum 12
  4. D. 7 numbers, sum 10

Correct answer: D. 7 numbers, sum 10

At iteration i, 2^i processes fork and each new child prints i. So 1 child prints 0, 2 print 1, 4 print 2: 7 numbers with sum 0 + 2 + 8 = 10.

More Operating Systems questions

Exams that ask this topic