CS FundamentalsHardGATE CS

What values are printed (in any order)? (Every fork() succeeds.)

What values are printed (in any order)? (Every fork() succeeds.)
int main() {
    int x = 1;
    if (fork() == 0) {
        x *= 2;
        if (fork() == 0) x *= 3;
    }
    printf("%d ", x);
}
  1. A. 1, 2, 6, 6
  2. B. 6, 6, 6
  3. C. 1, 2, 6
  4. D. 1, 6

Correct answer: C. 1, 2, 6

The parent keeps x = 1. The first child doubles to 2 and forks; its child multiplies its own copy by 3 to get 6, while it keeps 2. Each process has a private copy of x.

More Operating Systems questions

Exams that ask this topic