CS FundamentalsVery hardProduct company interview · GATE level

How many lines print the value 3, and what is the sum of all the values printed? (Assume every fork() succeeds.)

How many lines print the value 3, and what is the sum of all the values printed? (Assume every fork() succeeds.)
int main() {
    int c = 0;
    for (int i = 0; i < 4; i++)
        if (fork() == 0)
            c += i;
    printf("%d\n", c);
}
  1. A. 4 lines print 3; the sum is 48
  2. B. 2 lines print 3; the sum is 48
  3. C. 4 lines print 3; the sum is 24
  4. D. 1 line prints 3; the sum is 96

Correct answer: A. 4 lines print 3; the sum is 48

There are 2^4 = 16 processes, and each is identified by the set of iterations in which it was the child; its c is the sum of those i values. c = 3 for the sets {3}, {0, 3}, {1, 2} and {0, 1, 2} - note that being the child at i = 0 adds nothing - so 4 lines. Each i is in exactly half of the 16 sets, so the total is 8 x (0 + 1 + 2 + 3) = 48. 24 counts each i in only 4 processes; 2 forgets the sets that include i = 0.

More Operating Systems questions

Exams that ask this topic