Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

killing Parent process along with child process using SIGKILL

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.

like image 359
user3242440 Avatar asked Feb 19 '14 01:02

user3242440


People also ask

How do you kill a process with Sigkill signal?

The default signal is SIGTERM. kill is a built-in shell command. In the tcsh shell, kill [-signal] %job|pid … sends the specified signal (or if none is given, the TERM (terminate) signal) to the specified jobs or processes.

What happens to child process if parent is killed?

When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes).

How do you kill the parent process without killing your child?

If you are on the same terminal with the process, type ctrl-z to stop the parent, and the use ps -ef to find the PID of the php child. Use the kill lines above to effectively separate the child from the parent.


2 Answers

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.

like image 126
Jayesh Bhoi Avatar answered Sep 19 '22 17:09

Jayesh Bhoi


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.

like image 28
jpaugh Avatar answered Sep 21 '22 17:09

jpaugh