Search code examples
fork

Program flow, fork() with logic


I am trying to understand the flow of this simple C fork() code:

fork() && fork() || fork();
fork();
printf("forked ");

Output for me (g++) is:

forked forked forked forked forked forked forked forked forked 

Stepping over it doesn't really help me in understanding it.


Solution

  • fork() && fork() || fork();
    ^^^^^^^^^^^^^^^^
    Parent forks a child with return value 0 for the child process. 
    Since it is logical AND operator, the short-circuit evaluation applies, 
    so the child doesn’t go further. Parent goes on forking again(right-hand-side of AND). 
    There are 3 processes being composed of 2 children and 1 parent.
    
    
    
    fork() && fork() || fork();
                        ^^^^^^
                        Again parent forks one more and since OR operator
                        doesn’t apply short-circuit for latter child
                        (due to return type which is 0 and left-hand-side of OR op.), 
                        the latter child forks as well. There are totally 5 processes.
    
     fork()[fourth]; doubles prior number of processes 5*2 = 10 processes totally exist.
    

    Your output highly likely buffered. Try fprintf(stderr, "forked ");, fflush(stdout) or printf("forked\n”);.


    I think the following drawing helps more. enter image description here