简体   繁体   中英

How do I evaluate these fork() calls with the && and || operators in C?

I have below some code in C which uses the fork() system call, but I am just confused: how do I go about
solving what it does:

int main()
{
    fork();
    fork() || fork() && fork();
    fork();
    printf("ämit");
}

fork() && fork() || fork(); is evaluated some thing like this below:

       fork()
      /      \
    0/        \>0
 || fork()     && fork()
     /\            /   \
    /  \         0/     \>0
   *    *     || fork()  *
                /   \
               *     *

I need same kind of tree for fork() || fork() && fork() fork() || fork() && fork() . Can anyone tell me how I should achieve it?

If this is an interview question (likely) or homework (slightly less likely), you first calmly explain how you could evaluate it.

By that I mean, you state that the first, second and fifth forks are unconditional but the third and fourth depend on the second and third (and that these second and third will be happening in multiple processes).

That will show that you understand the concepts.

Then you explain that it doesn't really matter because, if any coder actually handed you code like that, there'd be some serious tar'n'feather action going on. Code like this monstrosity has no place in the real world and, although it's good for testing your understanding, you'll never encounter it in reality.

|| has lower precedence than && , and those operators short-circuit after evaluation of the first operand if it contains sufficient data ( || short-circuits if first operand is true and && short-circuits if first operand is false).

fork()||fork()&&fork() is equivalent to fork() || ( fork() && fork() ) fork() || ( fork() && fork() )

Therefore:

                                                       fork()
                                                     0/     \>0
                                                     /       *  ==> || short-circuits, no evaluation of  fork()&&fork()
                                                   fork()
                                                   0/    \>0
 && short-circuits, no evaluation of &&fork() ==>  *     fork()
                                                         /   \
                                                        *     *

For you first example it was equivalent to ( fork() && fork() ) || fork() ( fork() && fork() ) || fork() .

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