I can kill a child process by the parent process. But what happen if a parent process has more than one child processes?
For example in below code , there are one parent process and 6 child processes. How to kill the other six child processes immediately after the parent process termination?
If you run this code, parent is terminated after 5 seconds.After that child process are terminated after another 5 seconds(totally 10 seconds).
But I want to kill 6 child processes immediately after the parent process termination.So parent and 6 child process should be terminated after 5 seconds.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
for(int i=0;i<6;i++) // loop will run 6 times(there are 6 child processes.)
{
if(fork() == 0)
{
printf("Started [son] pid %d from [parent] pid %d\n",getpid(),getppid());
sleep(10); //child waits 10 seconds,then it exitted.
printf("Exitted [son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
//parent
sleep(5); //parent will wait 5 seconds than it will exit
printf("Parent terminated\n");
exit(0); //parent terminated.(how can I exit the the other 6 child processes too?)
}
Here's a probably more portable solution.
The fork(2)
system call will return the PID of your child processes, you can store the PIDs, and then you can use kill(2)
to send signal to the children and terminates them.
Notice that SIGKILL
and SIGTERM
signal may require some privileges of the parent process. If it doesn't have such privileges, you can send a SIGCONT
to the child process, and modify the SIGCONT
signal handler in your child process.
!!! Warning sign
From a signal handler using exit()
is not safe. I've just checked the manual man 7 signal
and found that it is not async safe. You can use _exit
, _Exit
or abort
Some pseudo code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void* handler(int sig){
_exit(0);
}
int main()
{
pid_t children[6];
for(int i=0;i<6;i++) // loop will run 6 times(there are 6 child processes.)
{
if((children[i] = fork()) == 0)
{
signal(SIGCONT,handler);
printf("Started [son] pid %d from [parent] pid %d\n",getpid(),getppid());
sleep(10); //child waits 10 seconds,then it exitted.
printf("Exitted [son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
//parent
sleep(5); //parent will wait 5 seconds than it will exit
for(int i=0;i<6;i++)
kill(children[I],SIGCONT);
printf("Parent terminated\n");
exit(0); //parent terminated.(how can I exit the the other 6 child processes too?)
}