[英]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.