加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 在管道左侧杀死进程

发布时间:2020-12-15 22:36:15 所属栏目:安全 来源:网络整理
导读:我在bash中有以下内容: foo |酒吧 我希望foo在脚本终止时死掉(使用TERM信号).不幸的是,他们都没有死.我试过这个: exec foo | bar 这绝对没有实现.然后我尝试了这个: function run() { "$@" pid=$! trap "kill $pid" EXIT wait}run foo | bar 再一次,没有.
我在bash中有以下内容:

foo |酒吧

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

exec foo | bar

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

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

run foo | bar

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

解决方法

通过杀死整个进程组而不仅仅是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

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

杀戮手册提到:

-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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读