16

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?

21

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.

2
  • Using "trap 'kill $BGPID; exit' SIGINT" I get a "SC2039: In POSIX sh, prefixing signal names with 'SIG' is undefined." I think you have to write trap 'kill $BGPID; exit' INT – Hettomei Aug 12 '19 at 9:31
  • @Hettomei Thanks for the input. I double check the trap man page and find that what you suggested is true: the standard requires the condition (the triggering signal) should not have the SIG prefix, and supporting SIG prefix is an extension. Updated the original answer. pubs.opengroup.org/onlinepubs/009695399/utilities/trap.html – lnyng Aug 15 '19 at 13:56
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.