CS FundamentalsModerateGATE CS · Amazon/Microsoft SDE MCQ

Which values are printed (in some order)? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)

Which values are printed (in some order)? (Every fork() succeeds, and each print is an unbuffered write, so nothing is printed twice through copied buffers.)
int main() {
    int x = 1;
    if (fork() == 0) {
        x += 2;
        if (fork()) x *= 3;
    } else {
        x += 5;
    }
    printf("%d ", x);
}
  1. A. 6, 9 and 9
  2. B. 6, 9 and 3
  3. C. 6 and 9 only
  4. D. 3, 6 and 18

Correct answer: B. 6, 9 and 3

The parent prints 1 + 5 = 6. The child makes x = 3 and forks: its parent side multiplies to 9, while the grandchild (fork() returned 0) keeps 3. Each process has its own copy of x.

More Operating Systems questions

Exams that ask this topic