Guybrush
Guybrush

Reputation: 201

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

Upvotes: 2

Views: 994

Answers (1)

isedev
isedev

Reputation: 19641

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.

Upvotes: 3

Related Questions