Search code examples
cforkwaitpid

C - Waiting for one child to terminate


I am creating multiple child processes in a loop. Each child will do it's thing and anyone of them can end first. (Not sure if relevant but: Each child also has a grandchild)

How do I wait for any child process to terminate and stop the others when one has finished ?

for(i=0; i<numberOfChildren; i++)
{
    pid = fork();
    if(pid < 0)
    {
        fprintf(stderr, "Error: fork Failed\n");
        return EXIT_FAILURE;
    }
    /* Child Process */
    if(pid == 0)
    {
        /* Do your thing */
    }
    /* Parent process */
    else
    {
        childrenPid[i]=pid;
    }
}

Solution

  • You can suspend the parent until one of its children terminates with the wait call and then kill the remaining children:

    #include <sys/types.h>
    #include <wait.h>
    
    int status;
    childpid = wait(&status)
    

    Then, if you have stored the process ID of all children you created in an array, you can kill the remaining children:

    #include <sys/types.h>
    #include <signal.h>
    
    for(i = 0; i < nchildren; i++)
        if (children[i] != childpid)
            kill(children[i],SIGKILL)
    

    where nchildren is an integer count of the number of children created and children is the array of pid_t of the children created.