如何在工作流树中表示fork()&& fork()?

y

在C语言中,fork()函数将为父进程返回非零值,为子进程返回零。

当使用&&或||之类的逻辑表达式时,试图了解这些代码的工作原理使我感到困惑。如何通过图论在树中显示它们?代码如何执行?

#include <stdio.h> 
#include <unistd.h> 
int main() 
{ 
   fork(); 
   fork() && fork(); // or fork() || fork() 

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

逻辑AND&&)和逻辑OR||)运算符都采用短路行为。

expr1 && expr2expr2如果expr1为逻辑0false),则不进行评估
expr1 || expr2expr2如果expr1为逻辑1true),则不进行评估

在逻辑短路的情况下,仅当第一个操作数不能完全确定结果时expr2才对第二个操作数进行评估expr1

假设fork()父流程和子流程中的所有调用均成功完成,则分叉流程树将如下所示:

 parent process
     |
     |
   fork()    // first fork
   -----     // below in the tree, RV is fork() returned value
     |
     |----child process [RV: 0]--
     |                          |
   [RV: child PID]              |
     |                          |
   fork() && fork()            fork() && fork()
   ------                      ------
     |                          |
     |                          |--child process [RV: 0]--
     |                          |                        |
     |                         [RV: X (child PID)]       |
     |                          |                      0 && fork()   
     |                          |                   // due to && short-circuiting behavior, 
     |                          |                   // fork() will not be called
     |                          |                        |
     |                          |                       Print "forked"
     |                          |                       Exit
     |                          |
     |                          |
     |                    X && fork()   // X is a non zero value and hence the fork() will be called
     |                         ------
     |                          |
     |                          |--child process [RV: 0]--
     |                          |                        |
     |                        [RV: child PID]            |
     |                          |                        |
     |                         Print "forked"           Print "forked"
     |                         Exit                     Exit
     |
     |--child process [RV: 0]--
     |                        |
   [RV: X (child PID)]        |
     |                      0 && fork()
     |                      // due to && short-circuiting behavior, fork() will not be called
     |                        |
     |                        |
     |                      Print "forked"
     |                      Exit
     |
X && fork()   // X is a non zero value and hence the fork() will be called
     ------
     |
     |--child process [RV: 0]--
     |                        |
   [RV: child PID]            |
     |                        |
     |                        |
   Print "forked"           Print "forked"
   Exit                     Exit

希望这可以帮助您了解执行情况。尝试fork() || fork()表达自己如果您还有其他问题,请告诉我。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章