Tuesday, February 23, 2010

Kill all child processes from shell script

Small and simple script. Creates Ctrl-C trap and kills all it's child processes in it. Nice to have when your script has many child processes which execution have to be stopped when main script is interrupted by Ctrl-C or other signal.


kill_child_processes() {
isTopmost=$1
curPid=$2
childPids=`ps -o pid --no-headers --ppid ${curPid}`
for childPid in $childPids
do
kill_child_processes 0 $childPid
done
if [ $isTopmost -eq 0 ]; then
kill -9 $curPid 2> /dev/null
fi
}

# Ctrl-C trap. Catches INT signal
trap "kill_child_processes 1 $$; exit 0" INT

for (( i = 0 ; i <= 5; i++ ))
do
# do something...
sleep 10 &
done

wait

2 comments:

Daemon said...

How would one integrate this into an existing bash script? Just putting it at the beginning of my script seems to have no effect.

Unknown said...

You have to press Ctrl+C to see how it works :)