CS FundamentalsHardProduct-company MCQ pattern

How many times is "x" printed? (fork() returns 0 in the child and a positive PID in the parent; assume it always succeeds.)

How many times is "x" printed? (fork() returns 0 in the child and a positive PID in the parent; assume it always succeeds.)
int main() {
    if (fork() && fork())
        fork();
    printf("x\n");
    return 0;
}
  1. A. 4
  2. B. 8
  3. C. 3
  4. D. 5

Correct answer: A. 4

&& short-circuits: the first child gets 0 and skips the second fork. The parent forks again; that second child gets 0, so the condition is false. Only the original parent enters the if and forks once more. Processes = parent + 3 children = 4.

More Operating Systems questions

Exams that ask this topic