tags:

views:

43

answers:

1
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

+5  A: 

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.

SLaks
Indeed. Probably the easiest for you would be to draw a tree, branching on each fork as it gets evaluated in the expression, with a child-branch (0) and the parent-branch (non-0).
Amadan
so does !fork() reverse the values for the child and parent. the parent getting a value 0 and the child 1
thegreattaurus
You might want to change the printf statements to include the process id, to make it clearer where the output is coming from.
jabley
that would be genius, I will use the getid() function
thegreattaurus
Thanks for the help guys. I have used stackoverflow for a while now, just to search for answers. This is my first time asking a question and I appreciate the quick and helpful responses.
thegreattaurus
You're welcome!
SLaks