using fork in an if-statement/ managing processes

前端 未结 2 1652
死守一世寂寞
死守一世寂寞 2021-01-26 11:31

I have this bit of code:

   printf(\"L1 \");

   if(fork() != 0) {
      printf(\"L2 \");

      if(fork() != 0) {

         printf(\"L3 \");
         fork();
          


        
相关标签:
2条回答
  • 2021-01-26 12:10

    In your code, the child of each fork proceeds directly to the printf("End"). Only the parent will print L1, L2, L3, so they'll only be printed once each, in that order. Mixed in with that output would be the Ends of the children (and the final end of the parent).

    0 讨论(0)
  • 2021-01-26 12:22

    If the fork() calls all fail, there'll only be one process, so it will print:

    L1 L2 L3 End
    

    If every fork() call succeeds, then:

    1. Assuming line buffered or fully buffered output,
    2. There will be 4 lots of print out, but their sequence is indeterminate, and could be (but probably won't be) interleaved on the output.
    3. Each output will start with L1 and end with End.
    4. When fork() returns a non-zero value, it is the parent process.
    5. The first if fails in the first child, so it prints L1 End.
    6. The first if passes in the parent, and the subsequent outputs will then include L2.
    7. The second if fails in the second child, so it prints L1 L2 End.
    8. The second if passes in the parent, and the subsequent outputs will then include L3.
    9. The third fork() creates two processes (or creates one and continues in the parent), both of which print L1 L2 L3 End.

    So, the output will consist of:

    L1 End
    L1 L2 End
    L1 L2 L3 End
    L1 L2 L3 End
    

    but the sequence is not guaranteed.


    After posting the analysis above, I checked it by running it, and the first sample run produced:

    L1 End 
    L1 L2 L3 End 
    L1 L2 End 
    L1 L2 L3 End 
    

    Note that if the output is non-buffered, then the output is different. L1 will appear once; L2 will appear once; L3 will appear once; and End will appear four times.

    One possible sequence is:

    L1 L2 End 
    L3 End 
    End 
    End 
    

    Another observed sequence (second of two runs) was:

    L1 L2 L3 End 
    End End 
    
    End 
    
    0 讨论(0)
提交回复
热议问题