CS FundamentalsVery hardGATE CS

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

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

Correct answer: D. 12

8 processes print; each value counts how many of the 3 forks returned 0 in that process's history, so the values are distributed binomially: {0: 1, 1: 3, 2: 3, 3: 1}. Sum = 3 × 4 = 12 (each fork contributes 1 to half of the final processes).

More Operating Systems questions

Exams that ask this topic