3

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(). Can anyone tell me how I should achieve it?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Amit Singh Tomar
  • 8,380
  • 27
  • 120
  • 199
  • 1
    Whoa! What are you trying to achieve? That gives me shivers.. – Alok Save Oct 25 '11 at 09:13
  • Note that one way of improving the program is to print the PID and parent PID of the process as it exits (plus a newline). This will tell you more about the process hierarchy (though there's no guarantee that the outputs from different programs will be separate, not interleaved). – Jonathan Leffler Feb 17 '14 at 18:14

2 Answers2

5

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
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().

Benoit
  • 76,634
  • 23
  • 210
  • 236