CS FundamentalsVery hardGATE CS

What is the sum of the values printed by all processes? (Every fork() succeeds.)

What is the sum of the values printed by all processes? (Every fork() succeeds.)
int main() {
    int n = 0;
    for (int i = 0; i < 3; i++) {
        if (fork() > 0) n++;
        else break;
    }
    printf("%d\n", n);
}
  1. A. 6
  2. B. 4
  3. C. 12
  4. D. 9

Correct answer: A. 6

Only the original keeps looping (each child breaks immediately), so there are 4 processes: the original prints 3 and each child prints the n it inherited at the moment it was created (0, 1, 2). Sum = 6.

More Operating Systems questions

Exams that ask this topic