CS FundamentalsHardTCS NQT · Infosys pattern

What does this program print? (Assume fork() succeeds; the order of the two lines may vary.)

What does this program print? (Assume fork() succeeds; the order of the two lines may vary.)
int x = 5;
int main() {
    if (fork() == 0) x++;
    else x--;
    printf("%d ", x);
    return 0;
}
  1. A. 5 5
  2. B. 6 6
  3. C. 6 5
  4. D. 6 4

Correct answer: D. 6 4

After fork the child and parent have separate copies of x (copy-on-write). The child increments its copy to 6, the parent decrements its own to 4. Changes in one are not seen by the other, even though x is global.

More Operating Systems questions

Exams that ask this topic