CS FundamentalsHardGATE CS · Amazon/Microsoft SDE MCQ

How many times is x printed? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)

How many times is x printed? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
int main() {
    if (fork() || fork())
        fork();
    printf("x");
}
  1. A. 4
  2. B. 6
  3. C. 8
  4. D. 5

Correct answer: D. 5

In the parent the first fork() is nonzero, so || short-circuits and it forks once more (2 processes). The first child evaluates the second fork(): its parent side is nonzero and forks again (2), and the new child gets 0 and skips the body (1). Total 5.

More Operating Systems questions

Exams that ask this topic