CS FundamentalsHardAmazon · Microsoft MCQ pattern

How many lines are printed in total? (Assume every fork() succeeds.)

How many lines are printed in total? (Assume every fork() succeeds.)
int main() {
    for (int i = 0; i < 3; i++) {
        if (fork() == 0)
            printf("%d\n", i);
    }
    return 0;
}
  1. A. 12
  2. B. 8
  3. C. 7
  4. D. 3

Correct answer: C. 7

Only a newly created child prints, once, at the moment it is created, and then continues the loop. Forks: 1 at i = 0, 2 at i = 1, 4 at i = 2, so 7 lines (one 0, two 1s, four 2s). 8 would count the original process, which never prints.

More Operating Systems questions

Exams that ask this topic