Search code examples
clinuxunixforksystems-programming

Why does this program print "forked!" 4 times?


Why does this program print “forked!” 4 times?

#include <stdio.h>
#include <unistd.h>

int main(void) {

  fork() && (fork() || fork());

  printf("forked!\n");
  return 0;
}

Solution

  • The first fork() returns a non-zero value in the calling process (call it p0) and 0 in the child (call it p1).

    In p1 the shortcircuit for && is taken and the process calls printf and terminates. In p0 the process must evaluate the remainder of the expression. Then it calls fork() again, thus creating a new child process (p2).

    In p0 fork() returns a non-zero value, and the shortcircuit for || is taken, so the process calls printf and terminates.

    In p2, fork() returns 0 so the remainder of the || must be evaluated, which is the last fork(); that leads to the creation of a child for p2 (call it p3).

    P2 then executes printf and terminates.

    P3 then executes printf and terminates.

    4 printfs are then executed.