3
 main()
    {
        fork() && fork() || fork();

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

//how is it printing fork 5 times instead of 8 times?

2 Answers2

4

Because of short circuiting.

If I rewrite this:

main()
{
    // fork() && fork() || fork();

    if (fork()) {
        if (!fork()) {
            fork();
        }
    } else {
        fork();
    }

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

After first fork you will have one process that will go into the else branch straight away and one that will continue. The one that goes into the else loop will fork just once (right branch). The one that goes into the inner one will fork once and its child will fork again.

  f
/   \
f   f
|
f
glglgl
  • 89,107
  • 13
  • 149
  • 217
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
1

because of the and operator. Remember and operator will terminate as soon as it hits a false. fork will return 0 (false) for either parent or child(forgot), and it will terminate the Boolean expression which skips the other 2 forks, that is why you will only print fork 5 times instead of 8

Steve
  • 11,696
  • 7
  • 43
  • 81