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

31,170

Solution 1

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

Solution 2

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

Solution 3

Jxh 's answer is nice. Howevr , maybe you can just give a signal hander for every children process after fork and let it call exit function . and you give a signal hander for parent and let it ignore the signal (like SIGUSR1). this may add the code lines but you don't need detect the process is parent or child in signal hander function.

Share:
31,170
Reuben Tanner
Author by

Reuben Tanner

Updated on August 03, 2021

Comments

  • Reuben Tanner
    Reuben Tanner over 2 years

    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.

  • puk
    puk over 10 years
    Hi Lidong, a small example would go a long way to illustrating what one should do =)