【问题标题】:Program flow, fork() with logic程序流程,带有逻辑的 fork()
【发布时间】:2019-06-22 11:49:54
【问题描述】:

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

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

我的输出(g++)是:

forked forked forked forked forked forked forked forked forked 

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

【问题讨论】:

  • 您可以将fork() 包装为具有其他副作用的函数。这可以帮助您更好地跟踪正在发生的事情

标签: fork


【解决方案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”);


我认为下面的图更有帮助。

【讨论】:

  • 这无疑是一个很好的答案,但我很愚蠢。你能为我分解fork() && fork(); fprintf(stderr, "forked\n"); 吗?仅此而已,单独考虑,周围没有其他代码。
  • @sid Nominal Animal我的主人说每个人都是人,每个人都有可能被卡住,不要表现得不好。它将打印 forked 3 次。开头 2 次(AND 运算符的左侧)。 fork 的结果之一是孩子返回的 0,另一个不是 0(即它是父母)。父级评估 AND 运算符的右侧并分叉一个孩子。这就是fork() && fork(); 的结果有两个孩子和一个父母的原因。第一个孩子不会评估 AND 运算符的 RHS。
  • @sid En passant,我认为这是一个很好的问题,即使是最有经验的人也会在这个问题上犯错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多