I don't understand this diagram of fork()


enter image description here

How we can get this process with this condition??schema of process?

    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);

Answers:


fork() splits a process in two, and returns 0 (if this process is the 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 failed to create a child process".

The diagram is a little confusing because of the way the processes (circles) correspond to the fork() calls in the loop. The three child processes of the main process are created when i is 0, 1, and 2 respectively (see the diagram at the bottom of this post).

Since the loop continues in both the parent and the child process from the point fork was called, this is how the forks happen:

  • i == 0: fork is called in the original parent. There are now two processes (the top one, and the left one).
  • i == 1: fork is called in the two existing processes. New children are the leftmost child on the second layer from the bottom, and the middle child on the third layer from the bottom. There are now four processes
  • i == 2: fork is called in all existing processes. New children are all remaining nodes (the bottom node, the two rightmost nodes in the second layer from the borrom, and the rightmost node in the third layer from the bottom)
  • i == 3: All 8 processes exit the loop

Here is the diagram again, with numbers indicating what the value of i was in the loop when the process was created:

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