Killing Running Bash Script Process Itself and All Child Processes In Linux

Posted on

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 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=)

2 comments

  1. `$$` is the Bash script’s process ID itself. If the purpose it to kill a process and all its child processes, replace `$$` with that process’ process ID.

Leave a Reply

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

Related Posts