程序流程,fork() 与逻辑

Program flow, fork() with logic

我试图理解这个简单的 C fork() 代码的流程:

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

我的输出 (g++) 是:

forked forked forked forked forked forked forked forked forked 

越过它并不能真正帮助我理解它。

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.

您的输出很可能已缓冲。尝试 fprintf(stderr, "forked ");fflush(stdout)printf("forked\n”);


我觉得下面的图更有帮助。