I do not understand this fork () diagram

enter image description here

How can we get this process with this condition? Process diagram?

    int main (int argc, char **argv) {
    int i;
    int pid;
       for (i= 0; i < 3; i++) {
            pid = fork();

            if (pid < 0) break;// with this condition i dont understand??

       }
           while (wait(NULL) != -1);
+5
source share
4 answers

fork()splits the process into two parts and returns 0 (if this process is a child) or the PID of the child (if this process is the parent) or -1 if the fork failed. So this line:

if (pid < 0) break;

Says "exit the loop if we were unable to create a child process."

The diagram is a bit confusing due to how the processes (circles) correspond to the calls fork()in the loop. Three child processes of the main process are created when ithey are 0, 1, and 2, respectively (see the diagram at the bottom of this message).

, fork, , :

  • i == 0: fork . ( ).
  • i == 1: fork . - , - .
  • i == 2: fork . - ( node, node )
  • i == 3: 8

, , i :

                 -1  <--- this is the  parent that starts the loop
              /   |  \
             0    1   2
           /  \   |
          1    2  2
          |
          2
+8

, fork: , , ( PID) .

, :

i=0 , , ( ). , , , i=1. , , i=1, . i=2. i=2, .

i=1, , i=2, .

.

, if (pid < 0) - .

+3

fork -1, fork . pid 0 . , , ; , fork, . fork , .

, . , , i fork.

+2

fork return -1 0 else, if (pid < 0) break; " , ".

, , - :

i=0, . p0.

fork(); p0 . p1.

i++ ( i 1), .

p0 p1, , fork();, . p2 p3.

i++, i 2, .

4 , , fork(); . p4, p5, p6, p7.

Each process increments it ito 3, and then, since the condition of the cycle is now false, the cycle finally ends.

Now process 8 arrives (separately) on the next line.

(In fact, each iteration doubles the number of processes, so if you change 3to, for example, 15you will have 2 ^ 15 processes at the end.)

+2
source

All Articles