dmx dmx - 1 year ago 82
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 :
    and I use
    sudo ./
    to run

  • The script in

sudo p1 > p1.txt && p2 > p2.txt && p3 > p3.txt

to stop my app I use
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.

sorry it is this instead (only one &)

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

Answer Source

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

#      ^^^^ - 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

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

sudo f1/ > logs/p1.txt & pids+=( "$!" )
sudo f2/ > 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download