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

前端 未结 2 551
半阙折子戏
半阙折子戏 2020-12-11 23:57

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


        
相关标签:
2条回答
  • || 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() )

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

    0 讨论(0)
  • 2020-12-12 00:22

    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.

    0 讨论(0)
提交回复
热议问题