简体   繁体   中英

how fork works with logical operators

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

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() 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM