Search code examples
c++operating-systemfork

Forking inside conditional statements


How would I calculate how many "hello world" are printed after the execution of this program. Based on how fork works, we know that fork returns non-zero value as a parent process, and a child process returns 0.

I have worked with fork() before, and calculating fork count when in loops, but have not done anything with conditional statements, how would I begin to break this problem down?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    (fork() && fork() || fork() && fork() || fork() && fork() && fork());
    printf("hello world");
    return 0;
}

Solution

  • To better understand what's going on you should try to draw a tree with parent and children processes.

    Consider that after a fork():

    • the parent process return a number > 0
    • child process return a number == 0

    that means:

    • && operator allows multiple children for the same parent because as soon as the pid=0 (child process) the result is 0 and the condition is no longer considered
    • || operator allows single child for the parent processes because as soon as the pid!=0 (parent process) the result is !=0 and the condition is no longer considered

    Visualizing the trees related with much simpler cases than yours:

    fork() && fork() && fork()

                                      P
                                    / | \
                                  C1 C2 C3
           
    

    fork() || fork() || fork()

                                          P
                                         /
                                        C1
                                       /
                                      C2
                                     /
                                   C3
    

    As a suggestion, if you want to understand more about what's going on and be able to build the tree, replace your printf() with:

    printf("hello world - pid %d, ppid %d\n", getpid(), getppid());
    

    so you can understand more easily how the process tree has been created.