Home > Net >  Process tree / Number of processes for fork()
Process tree / Number of processes for fork()

Time:04-09

I want to know the number of processes created for the below code. I got to know from my instructor the answer is 41 but I am unable to follow the same. Please explain the same with a process tree.

  void main() {
    for (i=0;i<2;i  ){
        fork();
        if(!fork()) {
            execl("/bin/ls","ls",NULL);
            fork();
        }
        fork();
     }
     fork();
  }

CodePudding user response:

This looks like a homework question. If we would draw a process tree for you, you might get some points now, but you will not learn how to analyze a program, and this may hurt you later. You will learn more by understanding how the program works. (Of course, this program is an academic example and not very useful except for learning.)

I suggest to mark the fork calls with letters.

int main(void) {
    for (int i = 0; i < 2; i  ) {
        fork();          /* A */
        if(!fork()) {    /* B */
            execl("/bin/ls","ls",NULL);
            fork();      /* C */
        }
        fork();          /* D */
    }
    fork();              /* E */
}

Take paper and pencil, write down what happens and draw a tree using the loop counter and the marked fork calls.

Example:

The program runs a loop for two cycles (0 and 1), the loop continues in all processes.

In parent P, loop cycle 0, fork A will create child 1.
P -(0,A)-> 1

Still in loop cycle 0, both P and 1 will run the fork B inside the condition, creating a new child each.
P -(0,B)-> 2, 1 -(0,B)-> 3.

Think about the meaning of the condition and decide which processes run the conditional block.

Think about what happens after execl, e.g. process x executes ls, resulting in ...

Some processes (name them) will reach D and create a child each, all will continue with loop cycle 1...

etc.

To see what happens you could add some output after every fork to display what happens: which loop index, which fork, is the process parent or child of this fork, PID, parent PID. And before the execl display which PID is about to call it. (Note that buffered output like printf may show unexpected behavior in combination with fork, so it might be better to use sprintf and write.) Running the program will produce output that could help you to draw a process tree. It is even possible to format the output in a way that a tree could be generated automatically using graphviz or PlantUML. All these are advanced topics.

  • Related