Search code examples
linuxprocessforkwaitpid

Child processes waiting on each other


I created three processes and I want to synchronize their work. Specifically, I want the first process to wait on the second, second on third. Basically execute them in the reverse order they were created in.

Here is what i did so far.

for (; i < 3 ; i++){
        pids[i] = fork();
        if (pids[i] == 0)
           break;
}
if (pids[i] != 0){
    wait(); // Main thread has to wait..    
}
else{               
     if (i == 0){
        waitpid(pids[1], &status, 0);       
        printProcessInfo(0);        
     }
     else if (i == 1){
        waitpid(pids[2], &status, 0);       
        printProcessInfo(1);        
          }
     else if (i == 2){
        printProcessInfo(2);        
     }              
}

I am using i to check which child process I am in because I am assuming I get the correct i in the child process, so if i = 0, i am in fact in the fist child. Is this assumption true? In any case I don't get the order I want, in fact the processes get executed in their natural order, bypassing the waitpid calls I placed. Any ideas?


Solution

  • No, you are getting more then 3 process.

    Consider a simplified version (this is just removed wait... you do the same number of fork):

    for (i=0; i < 3 ; i++){
        pids[i] = fork();
    }
    

    Because you do the fork inside a for-loop, without checking the return value. Both parent and child will get its own child.

        [###############PARENT###############]
              |           |           |
             i=0         i=1         i=2
              |           |           |
            [ a0 ]      [ b0 ]      [ c0 ]
             / \          |
           i=1 i=2       i=2
           /     \        |
         [a1]   [a2]    [ b1 ]
          |
         i=2
          |
         [a3]
    

    You have to break the loop after checking the return value for fork.