Bash:当脚本终止时,如何终止脚本的子进程?

Ivi*_*ava 11 linux bash subprocess termination

该问题适用于以下脚本:

脚本

#!/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!"
Run Code Online (Sandbox Code Playgroud)

目前的行为

Ctrl+C在控制台中按下会终止脚本,但不会终止已在运行的grep进程.

And*_*rew 16

在陷阱中写入陷阱Ctrl+c并杀死所有子进程.把这个放在你的wait命令之前.

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

trap handle_sigint SIGINT
Run Code Online (Sandbox Code Playgroud)