Plug function process graph, valid and invalid outputs

printf("L1 \n");
  if (fork() != 0) {
    printf("L2 \n");
    if (fork() != 0) {
      printf("L3 \n");
      fork();
    }
  }
printf("End \n");

It's hard for me to understand this code. Can someone explain / show what the process graph will look like? In addition, a valid and invalid sequence.

My thought on the process schedule was something like this:

L1 will contain two processes L2, then in each process L2 2 processes L3 will be executed, and each process L3 will support the final processes. Is it correct?

The valid sequence for me was L1, L2, L3, End

L2, L1, End will be invalid, because L1 must be before L2, L2 depends on L1.

-1
source share
1 answer

, .

1.  printf("L1 \n");
2.  if(fork() != 0) {
3.    printf("L2 \n");
4.    if(fork() != 0) {
5.      printf("L3 \n");
6.      fork();
7.    }
8.  }
9.  printf("End \n");

, PID 1000 (, , , , ).

Line1:

PID==1000 L1. :

:

           1000

:

L1

Line2:

Process PID==1000 forks, (, PID==1001). man 2 fork PID==1000 if, fork() 0 .

PID==1000 3, L2, 5, PID==1001 9 if, End. :

:

  -------------- 1000
  |
  |
 1001

:

L1
L2
End

4:

PID==1000 , PID==1002.

, PID==1002 9, End, fork() 0 , PID==1000 5, L3, 6. :

:

   ------------ 1000
   |              |
   |              |
  1001          1002

:

L1
L2
End
L3
End

6:

PID==1000 . PID==1003. 9, End. , , :

:

   ------------- 1000 --------------
   |               |               |
   |               |               |
  1001           1002            1003

:

L1
L2
End
L3
End
End
End

, printf() , getpid(2), , . :

1.  printf("(pid %d)\tL1\n", (int) getpid());
2.  if (fork() != 0) {
3.      printf("(pid %d)\tL2\n", (int) getpid());
4.      if (fork() != 0) {
5.          printf("(pid %d)\tL3\n", (int) getpid());
6.          fork();
7.      }
8.  }
9.  printf("(pid %d)\tEnd\n", (int) getpid());
+1
source

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


All Articles