CS FundamentalsModerateGATE CS · Amazon/Microsoft SDE MCQ

Which letters are printed, and how many times each? (Every fork() succeeds, and each print is an unbuffered write.)

Which letters are printed, and how many times each? (Every fork() succeeds, and each print is an unbuffered write.)
int main() {
    if (fork() == 0) {
        if (fork() == 0) printf("C");
        else printf("B");
    } else {
        fork();
        printf("A");
    }
}
  1. A. A once, B once, C once
  2. B. A twice, B twice, C once
  3. C. A twice, B once, C once
  4. D. A once, B twice, C twice

Correct answer: C. A twice, B once, C once

The original takes the else branch and forks, so it and its new child each print A. The first child forks again: it prints B and its own child prints C.

More Operating Systems questions

Exams that ask this topic