CS FundamentalsVery hardGATE CS · Amazon/Microsoft SDE MCQ

How many numbers are printed, and what is their sum? (Every fork() succeeds, and each print is an unbuffered write.)

How many numbers are printed, and what is their sum? (Every fork() succeeds, and each print is an unbuffered write.)
int main() {
    for (int i = 0; i < 3; i++) {
        printf("%d", i);
        fork();
    }
}
  1. A. 14 numbers, sum 20
  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

The print comes before each fork: at i = 0 one process prints 0, at i = 1 two print 1, at i = 2 four print 2. That is 7 numbers summing to 0 + 2 + 8 = 10. With stdout buffered to a pipe the copies would multiply, which is why unbuffered writes are assumed.

More Operating Systems questions

Exams that ask this topic