How to use Ctrl+C to kill all background processes started in a Bash script?
ArchLinux (Manjaro).
I'm running one bash file. It runs 2 processes (commands), using &
.
But when I press Ctrl+C to stop the program - one process dies, and the other continues to work.
How do I stop both processes? Or how do I write a new script for killing these two processes?
Update: trap
requires removing SIG
prefix on condition, although some shells support including it. See comment below.
The ampersand "&" runs a command in the background in a new process. When its parent process (the command that runs the bash script in your case) ends, this background process will reset its parent process to init (process with PID
1), but will not die. When you press ctrl+c
, you are sending an interrupt signal to the foreground process, and it will not affect the background process.
In order to kill the background process, you should use the kill
command with the PID
of the most recent background process, which could be obtained by $!
.
If you want the to use ctrl+c
to kill both the script and background process, you can do this:
trap 'kill $BGPID; exit' INT
sleep 1024 & # background command
BGPID=$!
sleep 1024 # foreground command of the script
trap
modifies the trap handler of the SIGINT
(trap
requires removing the SIG
prefix but some shell may support including it) so the script will kills the process with $BGPID
before it exits.
Programs can ignore Ctrl+c
signal, as they can ignore SIGTSTP as well
You can try Ctrl+z
in most shells (not always but most of the time)
There are some signals that can not be ignored by the process: SIGKILL, SIGSTOP. You can send the kill command. To kill your frozen process, you have to find the process ID (PID).
use pgrep or ps and then kill it
% kill -9 PID