繁体   English   中英

如何杀死管道后台进程?

[英]How can I kill piped background processes?

示例会话:

- cat myscript.sh 
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
# here is were I want tail and grep to die
echo "more code here"

- ./myscript.sh

- ps
  PID TTY          TIME CMD
15707 pts/8    00:00:00 bash
20700 pts/8    00:00:00 tail
20701 pts/8    00:00:00 grep
21307 pts/8    00:00:00 ps

如您所见,tail和grep仍在运行。


像下面这样的东西会很棒

#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"

但这只能杀死grep,而不是尾巴。

虽然整个管道在后台执行,但只有grep进程的PID存储在$! 你想告诉kill杀死整个工作。 您可以使用%1 ,这将终止当前shell启动的第一个作业。

#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"

即使您刚刚终止grep进程, tail进程也应该在下次尝试写入标准输出时退出,因为当grep退出时该文件句柄被关闭。 取决于example.log更新的频率,几乎可以立即更新,或者可能需要一段时间。

你可以在脚本的末尾添加kill %1

这将杀死创建的first背景,这样就不需要找出pids等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM