killing Parent process along with child process using SIGKILL

懵懂的女人 提交于 2019-12-21 17:24:53

问题


I am writing one shell script in which I have parent process and it has child processes which are created by sleep & command. Now I wish to kill the parent process so that the child process will be also killed. I was able to do that this with below command:

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

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


回答1:


When you kill a process alone, it will not kill the children.

You have to send the signal to the process group if you want all processes for a given group to receive the signal.

kill -9 -parentpid

Otherwise, orphans will be linked to init.

Child can ask kernel to deliver SIGHUP (or other signal) when parent dies by specifying option PR_SET_PDEATHSIG in prctl() syscall like this:

prctl(PR_SET_PDEATHSIG, SIGHUP);

See man 2 prctl for details.




回答2:


Sending the -9 signal (SIGKILL) to a program gives no chance for it to execute its own signal handlers (e.g., your trap statements). That is why the children don't get killed automatically. (In general, -9 gives no chance for the app to clean up after itself.) You have to use a weaker signal to kill it (such as SIGTERM.)

See man 7 signal for details.



来源:https://stackoverflow.com/questions/21869242/killing-parent-process-along-with-child-process-using-sigkill

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!