how fork works with logical operators

一曲冷凌霜 提交于 2019-12-20 06:16:01

问题


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


回答1:


fork() returns 0 (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 call fork 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.



来源:https://stackoverflow.com/questions/3868951/how-fork-works-with-logical-operators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!