Killing Parent process with child process using SIGKILL

I am writing a single shell script in which I have a parent process and it has child processes created by the sleep & command. Now I want to kill the parent process so that the child process is also killed. I was able to do this with the following command:

 trap "kill $$" SIGINT trap 'kill -HUP 0' EXIT trap 'kill $(jobs -p)' EXIT 

These commands work with kill [parent_process_ID] , but if I use kill -9 [parent_process_ID] , only the parent process will be killed. Please guide me further to achieve this functionality, so that when I kill the parent process with any command, then the child process must also be killed.

+4
source share
2 answers

When you kill only a process, it will not kill children.

You must send a signal to a process group if you want all processes for this group to receive a signal.

 kill -9 -parentpid 

Otherwise, the orphans will be bound to init .

The child may ask the kernel to deliver SIGHUP (or another signal) when the parent dies by specifying the PR_SET_PDEATHSIG option in prctl() syscall, like this:

 prctl(PR_SET_PDEATHSIG, SIGHUP); 

See man 2 prctl more details.

+8
source

Sending -9 signal ( SIGKILL ) to the program does not allow you to execute your own signal handlers (for example, your trap statements). That is why children are not automatically killed. (In general, -9 application from clearing after itself.) To do this, use a weaker signal (for example, SIGTERM .)

See man 7 signal more details.

+2
source

All Articles