CS FundamentalsVery hardGATE CS · Amazon/Microsoft SDE MCQ

How many numbers are printed in total, and what is their sum? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)

How many numbers are printed in total, and what is their sum? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
int main() {
    for (int i = 0; i < 3; i++)
        if (fork() && i % 2 == 0)
            printf("%d ", i);
}
  1. A. 7 numbers, sum 8
  2. B. 5 numbers, sum 8
  3. C. 4 numbers, sum 8
  4. D. 5 numbers, sum 10

Correct answer: B. 5 numbers, sum 8

At i = 0 one process forks and its parent side prints 0. At i = 1 nothing prints. At i = 2 four processes exist, and each one's parent side prints 2. That is 5 numbers: 0 + 4 × 2 = 8.

More Operating Systems questions

Exams that ask this topic