What would be the best way to kill all the processes of a parent but not the parent? Let's say I have an undetermined number of child processes that I've forked and on a given alarm, in my signal handler, I'd like to kill all my child processes but keep myself running for various reasons.
As of now, I am using kill(-1*parentPid, SIGKILL) but this kills my parent along with its children.
I held a very incorrect assumption about this relationship. I thought that if I kill the parent of a process, it kills the children of that process too. However, this is incorrect. Instead, child processes become orphaned, and the init process re-parents them.
If a child process has no parent process, then the child process is created directly by the kernel. If a child process exits or is interrupted, then a SIGCHLD signal is sent to the parent process to inform about the termination or exit of the child process.
In chrome on Windows, the child processes are in a job object and so the OS takes care of killing them when the parent process dies.
One way to accomplish this is to deliver some signal that can be caught (not SIGKILL
). Then, install a signal handler that detects if the current process is the parent process or not, and calls _exit()
if it is not the parent process.
You could use SIGUSR1
or SIGUSR2
, or perhaps SIGQUIT
.
I've illustrated this technique here.
Optionally (as suggested by Lidong), the parent process can use SIG_IGN
on the signal before issuing the kill()
command.
signal(SIGQUIT, SIG_IGN);
kill(0, SIGQUIT);
you can set the child process a new process group at the fork time, and while you want to kill the child process and its descendants, you can use killpg, example code as:
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
void parent(pid_t pid) {
killpg(pid, SIGKILL);
}
void child(void) {
if (-1 == setsid())
return;
while(1) {
sleep(1);
printf("child\n");
}
}
int main() {
pid_t pid;
switch ((pid=fork())) {
case 0: // child
child();
break;
default: // parent
getchar();
getchar();
parent(pid);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With