fork如何与逻辑运算符一起使用 [英] how fork works with logical operators

查看:91
本文介绍了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与逻辑运算符一起使用时会发生什么.

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.

我对c/c ++来说还很陌生,所以请放轻松.谢谢

I am pretty new to c/c++ so go easy on me. Thanks

推荐答案

fork()向子进程返回0(false),向父进程返回非零(true).

fork() returns 0 (false) to the child process, and non-zero (true) to the parent process.

您可以将逻辑运算符应用于这些布尔值.

You can apply logical operators to these booleans.

请记住,逻辑运算符会短路,因此0 || fork()根本不会调用fork.

Remember that logical operators will short-circuit, so 0 || fork() will not call fork at all.

如果您仔细阅读代码并考虑每个fork()调用将返回的内容,您应该能够弄清楚.

If you read carefully through the code and think about what each fork() call will return, you should be able to figure it out.

这篇关于fork如何与逻辑运算符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆