Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill all child processes of a parent but leave the parent alive

Tags:

c

unix

process

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.

like image 558
Reuben Tanner Avatar asked Aug 25 '13 20:08

Reuben Tanner


People also ask

What happens to the Childs If you kill a parent process?

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.

Can a child process exist without a parent?

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.

What happens to child process when parent is killed Windows?

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.


2 Answers

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);
like image 101
jxh Avatar answered Sep 28 '22 03:09

jxh


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;
}
like image 38
f_x_p Avatar answered Sep 28 '22 04:09

f_x_p