我在bash中有以下内容:
foo | 酒吧
foo脚本终止时我想死(使用TERM信号).不幸的是,他们都没有死.我试过这个:
exec foo | bar
Run Code Online (Sandbox Code Playgroud)
这绝对没有实现.然后我尝试了这个:
function run() {
"$@" &
pid=$!
trap "kill $pid" EXIT
wait
}
run foo | bar
Run Code Online (Sandbox Code Playgroud)
再一次,没有.现在我还有一个进程,当我终止父进程时,它们都没有死掉.
通过终止整个进程组而不是仅终止bash(父进程),您也可以向所有子进程发送终止信号。语法示例是:
kill -SIGTERM -$!
kill -- -$!
Run Code Online (Sandbox Code Playgroud)
例子:
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
Run Code Online (Sandbox Code Playgroud)
请注意,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.
Run Code Online (Sandbox Code Playgroud)