fork 如何与逻辑运算符一起使用
main()
{
if (fork() || (fork() && fork()))
printf("AA\n");
else if (!fork())
printf("BB\n");
else
printf("CC\n");
}
我运行了以下代码并得到结果 AA AA CC BB CC BB。 虽然我了解 fork 的工作原理,但我不明白它对逻辑运算符的作用。我们班的老师要我们给出这份作业的答案。虽然我可以轻松运行这个程序,但我想知道到底发生了什么。 任何人都可以解释或引导我访问一个网站,了解使用 fork 和逻辑运算符时会发生什么情况。
我对 c/c++ 还很陌生,所以对我来说要轻松一些。谢谢
main()
{
if (fork() || (fork() && fork()))
printf("AA\n");
else if (!fork())
printf("BB\n");
else
printf("CC\n");
}
I have run the following code and get the results AA AA CC BB CC BB.
While I understand how fork works, I don't understand what it does with logical operators. The teacher in our class wants us to give the answers for this homework. While I can easily run this program, I would like to know what happens exactly.
Can anyone explain or direct me to a website to what happens when using fork with logical operators.
I am pretty new to c/c++ so go easy on me. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fork()
将0
(false) 返回给子进程,将非零 (true) 返回给父进程。您可以对这些布尔值应用逻辑运算符。
请记住,逻辑运算符会短路,因此
0 || fork()
根本不会调用fork
。如果您仔细阅读代码并思考每个
fork()
调用将返回什么,您应该能够弄清楚。fork()
returns0
(false) to the child process, and non-zero (true) to the parent process.You can apply logical operators to these booleans.
Remember that logical operators will short-circuit, so
0 || fork()
will not callfork
at all.If you read carefully through the code and think about what each
fork()
call will return, you should be able to figure it out.