简体   繁体   中英

Exit all processes that shell started

I have a simple bash script to run a given number of processes:

#!/bin/bash
# usage: ./run-abt.sh <agent count> <responder port> <publisher port>
echo "./abt-monitor 127.0.0.1 $2 $3 $1"
exec ./abt-monitor 127.0.0.1 $2 $3 $1 &
for (( i=1; i<=$1; i++ ))
do
    echo "Running agent $i";
    exec ./abt-agent 127.0.0.1 $2 $3 $i $1 > $i.txt &
done

What I need to add is when user press Ctrl+C and control returns to the bash, all processes created by run-abt.sh to kill.

Add this line to the beginning of your script:

trap 'kill $(jobs -p)' EXIT

When your script receives the interrupt signal from the Control-C (or any other signal, for that matter), it will terminate all the child processes before exiting itself.

At the end of the script, add a call to wait so that the script itself exit naturally) before the background processes complete, so that the signal handler installed above has a chance to run. That is,

for (( i=1; i<=$1; i++ ))
do
    echo "Running agent $i";
    exec ./abt-agent 127.0.0.1 $2 $3 $i $1 > $i.txt &
done    
# There could be more code here. But just before the script would exit naturally,...
wait         

Use the trap builtin:

trap handler_func SIGINT

You'll have to store and manage the pids of the child processes separately, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM