dmx dmx - 2 months ago 13
Linux Question

kill processes started in parallel

I start my app by starting many processes, I use a script (bash) to start it.


  • The filemane is :
    start.sh
    and I use
    sudo ./start.sh
    to run

  • The script in
    start.sh
    is:



#!/bin/sh
sudo p1 > p1.txt && p2 > p2.txt && p3 > p3.txt


to stop my app I use
ctrl-c
but not all processes stop. I know I could find with
ps aux | less | grep ...
, this seems long and I want to know if there is and easy wait to stop my processes.

update
sorry it is this instead (only one &)

sudo f1/p1.py > logs/p1.txt & sudo f2/p2.sh > logs/p2.txt & sudo nodemon f3/p3.js > logs/p3.txt

Answer

Store the PIDs, and set a trap to kill them when signaled or on exit:

#!/bin/bash
#      ^^^^ - NOT /bin/sh, as this code uses arrays

pids=( )

# define cleanup function
cleanup() {
  for pid in "${pids[@]}"; do
    kill -0 "$pid" && kill "$pid" # kill process only if it's still running
  done
}

# and set that function to run before we exit, or specifically when we get a SIGTERM
trap cleanup EXIT TERM

sudo f1/p1.py > logs/p1.txt & pids+=( "$!" )
sudo f2/p2.sh > logs/p2.txt & pids+=( "$!" )
sudo nodemon f3/p3.js > logs/p3.txt & pids+=( "$!" )

wait # sleep until all background processes have exited, or a trap fires
Comments