CS FundamentalsHardGATE CS

What is printed (ignoring order)? (Every fork() succeeds.)

What is printed (ignoring order)? (Every fork() succeeds.)
int main() {
    for (int i = 0; i < 3; i++) {
        if (fork() == 0) {
            printf("%d ", i);
            exit(0);
        }
    }
    for (int i = 0; i < 3; i++) wait(NULL);
}
  1. A. 0 1 1 2 2 2 2
  2. B. 0 1 2 0 1 2
  3. C. 0 1 2
  4. D. 0 0 0

Correct answer: C. 0 1 2

Each child prints its i and exits immediately, so only the parent keeps forking: three children print 0, 1 and 2 once each (in some order). Without exit(0), children would continue the loop.

More Operating Systems questions

Exams that ask this topic