Search code examples
cunixprocess

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


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.


Solution

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