杀死管道左侧的过程

问题描述 投票:5回答:2

我在bash中有以下内容:

foo |酒吧

我希望foo在脚本终止时死掉(使用TERM信号)。不幸的是,他们都没有死。我试过这个:

exec foo | bar

这绝对没有实现。然后我尝试了这个:

function run() {
    "$@" &
    pid=$!
    trap "kill $pid" EXIT
    wait
}

run foo | bar

再一次,没有。现在我还有一个进程,当我终止父进程时,它们都没有死掉。

bash process pipe
2个回答
1
投票

通过杀死整个进程组而不仅仅是bash(父进程),您也可以将kill信号发送给所有子进程。语法示例如下:

kill -SIGTERM -$!
kill -- -$!

例:

bash -c 'sleep 50 | sleep 40' & sleep 1; kill -SIGTERM -$!; wait; ps -ef | grep -c sleep
[1] 14683
[1]+  Terminated              bash -c 'sleep 50 | sleep 40'
1

请注意,wait在这里等待bash被有效地杀死,这需要几毫秒。另请注意,最终结果(1)是'grep sleep'本身。 3的结果表明这不起作用,因为两个额外的睡眠过程仍将运行。

kill手册提到:

-n
where n is larger than 1. All processes in process group n are signaled.
When an argument of the form '-n' is given, and it is meant to denote a
process group, either the signal must be specified first, or the argument
must be preceded by a '--' option, otherwise it will be taken as the signal
to send.

0
投票

我会使用一个命名管道,这样可以更容易地获得foo的进程ID。

trap 'kill $foo_pid; rm -f foo_out' EXIT

mkfifo foo_out
foo > foo_out & foo_pid=$!
bar < foo_out
© www.soinside.com 2019 - 2024. All rights reserved.