Home > Software engineering >  Why is my parent not waiting for each child?
Why is my parent not waiting for each child?

Time:04-16

Why is this program not waiting for all children? There are always 2 that are not finished when the parent's wait(NULL) recognizes that all children finished.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>

void foo(int* pointer) {
    //some code...
    return;
}



int main() {
    //some vars
    int var = 0;
    int *pointer = &var;
    pid_t pid = 0;
    
    
    //create 10 children
    for(int i = 0; i < 10; i  ) {
        pid = fork();
        if(pid == 0) { 
            foo(pointer);
            printf("back from foo()\n");
            //exit(0);              //do I need exit(0) here to terminate all children??? or just return ?
            return 0;
        }
    }
    
    printf("waiting for children...\n");
    wait(NULL);                             
    printf("all children finished...\n");   
    return 0;
}

The output is always the following:

back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
waiting for children...
all children finished...
back from foo()
back from foo()

That some children are back from foo before all children are created is understandable but why are some still in work when the parent stops waiting? Have I messed something up with the usage of exit(0); or/and return 0; at each children?

Thank you in advance! <3

CodePudding user response:

In a comment in the code, you ask:

// do I need exit(0) here to terminate all children or just return?

Given that the code is in main(), return(0); and exit(0); are equivalent. In any other function, it is almost certain that you'd need exit(0);. Personally, I'd use exit(0); in main() too, as protection against future changes that move the code into another function after all. And note that the exit(0): only terminates the current process, which is a child process given where the exit(0); call would be placed.

The wait() function waits for a single child to terminate. You must use a loop to wait for all children:

int corpse;
int status;
while ((corpse = wait(&status)) > 0)
    print("Child %d exited with status 0x%.4X\n", corpse, status);

You ask:

Have I messed something up with the usage of exit(0); or/and return 0; in each child?

No: you've messed up by not using wait() in a loop.

If you are familiar with the shell's wait command, you may be aware that it waits for all child processes to terminate. The wait() system call is different from the shell command.

CodePudding user response:

From man wait (NB: the "one of" part):

The wait() system call suspends execution of the calling thread until one of its children terminates.

  • Related