Using fork in if-statement / management processes

I have this bit of code:

   printf("L1 ");

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

      if(fork() != 0) {

         printf("L3 ");
         fork();
      }
   }
printf("End \n");

As an exercise, I am trying to figure out some examples of valid / invalid output that may result from running this code (without actually running it).

I'm still a bit confused about how the fork () method works exactly in an if-statement. I know that once it is called, it returns twice, indicating that it created two processes. So, if I did something like

printf("L1 ");
fork();
printf("L2 ");

I would get L1 L2 L2

But I'm still messy about how it works in expressions like the first bit of code.

Here's what I think are a few valid / invalid outputs:

Valid: L1 L1 L2
       L1 L2 L3
       L1 L2 L1

Invalid: (Anything hat doesn't start with L1)
      L1 L2 L2
      L1 L3 L2

? , if-, , fork() ? /?

0
2

fork() , , :

L1 L2 L3 End

fork() , :

  • , ,
  • 4 , (, , ) .
  • L1 End.
  • fork() , .
  • if , L1 End.
  • if , L2.
  • if , L1 L2 End.
  • if , L3.
  • fork() ( ), L1 L2 L3 End.

, :

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

.


, , :

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

, , . L1 ; L2 ; L3 ; End .

:

L1 L2 End 
L3 End 
End 
End 

( ):

L1 L2 L3 End 
End End 

End 
+1

printf("End"). L1, L2, L3, . End ( ).

+1

Source: https://habr.com/ru/post/1535209/


All Articles