In Linux, how to kill a process and all its child processes?
For example, a Bash script A starts B, B starts C and C calls
I would like to kill A and all its child processes all together. How to do this?
There are possibly many answers to this question. One of the good and reliable answer is to make use of the session ID (SID).
By default without any changes to the session ID of child processes (this is the case for most tools/shell scripts), the child processes are in the same session whose ID is the Bash script’s process ID (
We can find out all the processes’ IDs using
ps within the Bash script:
ps -s $$ -o pid=
Then we can kill them using the process IDs.
To wrap up, a single statement will kill all the child processes of the current running Bash script:
kill $(ps -s $$ -o pid=)