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

标签 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!"

当前行为

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

最佳答案

Ctrl+c 编写一个陷阱,并在陷阱中杀死所有子进程。将其放在您的 wait 命令之前。

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

trap handle_sigint SIGINT

关于linux - Bash:当脚本终止时,如何终止脚本的子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7817637/

相关文章:

linux - 从文本文件进入一行并编辑它

bash - 从 Vim 中执行 Bash 函数 - 我该怎么做?

python - 让子进程正确格式化

linux - Kali Linux 中自动启动脚本的其他方法?

linux - 如何使用 Perl 脚本列出文件的行号?

LInux 用进程状态检查替换 sleep 调用

linux - 使用 .s 文件设置文件类型和注释键映射

linux - for循环从文件运行命令

python: subprocess.Popen() 行为

python - 子进程在 Windows 上有错误的 pid