Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How do I make sub-processes of a script be terminated, when the script is terminated?

The question applies to a script such as the following:

Script

#!/bin/sh

SRC="/tmp/my-server-logs"

echo "STARTING GREP JOBS..."
for f in `find ${SRC} -name '*log*2011*' | sort --reverse`
do
    (
        OUT=`nice grep -ci -E "${1}" "${f}"`
        if [ "${OUT}" != "0" ]
        then
            printf '%7s : %s\n' "${OUT}" "${f}"
        else
            printf '%7s   %s\n' "(none)" "${f}"
        fi
    ) &
done

echo "WAITING..."
wait

echo "FINISHED!"

Current behavior

Pressing Ctrl+C in console terminates the script but not the already running grep processes.

like image 351
Ivivi Vavava Avatar asked Oct 19 '11 07:10

Ivivi Vavava


1 Answers

Write a trap for Ctrl+c and in the trap kill all of the subprocesses. Put this before your wait command.

function handle_sigint()
{
    for proc in `jobs -p`
    do
        kill $proc
    done
}

trap handle_sigint SIGINT
like image 141
Andrew Avatar answered Nov 16 '22 03:11

Andrew