程序流,带有逻辑的fork()

时间:2019-06-22 11:49:54

标签: fork

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

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

对我来说(g ++)的输出是:

forked forked forked forked forked forked forked forked forked 

单步执行并不能真正帮助我理解它。

1 个答案:

答案 0 :(得分:1)

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”);


我认为以下附图会有所帮助。 enter image description here