In Linux, how to kill a process and all its child processes?

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 rsync.

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.

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 Bash script:

kill $(ps -s $$ -o pid=)
Leave a Reply

Your email address will not be published. Required fields are marked *