CS FundamentalsHardGATE CS

How many times is "x" printed? (Every fork() succeeds; output is not buffered.)

How many times is "x" printed? (Every fork() succeeds; output is not buffered.)
int main() {
    for (int i = 0; i < 3; i++) {
        fork();
        if (i == 1) printf("x\n");
    }
}
  1. A. 4
  2. B. 8
  3. C. 2
  4. D. 6

Correct answer: A. 4

The print runs once in each process alive right after the second fork, i.e. 2² = 4 processes. The third fork happens after the print, so its children print nothing.

More Operating Systems questions

Exams that ask this topic