30

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?

Ievgen
  • 403

3 Answers3

31

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.

lnyng
  • 811
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
Romano
  • 64
1

For multiple background processes

#! /bin/bash -e

Make sure to kill each one of these individually if

stopping processing midway through as they will just keep going otherwise

trap 'for pid in ${main_pids[*]}; do kill $pid done; exit' INT

main_pids=() for i in "${!STATES_SETS[@]}"; do time python script.py & main_pids[${i}]=$! done

Wait for all pids to ensure all is well

for pid in ${main_pids[*]}; do wait $pid done

In VSCode, it seems that if you try to view the process id, it gives you some strange id that doesn't match what you can see with ps. The code will still work however. Can check with: ps -aux | grep script.py