how fork works with logical operators

2019-03-06 05:37发布

问题:

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.



标签: c fork