杀死管道进程的好方法?
我想在创建 shell 时处理它的每个标准输出行。我想获取 test.sh 的输出(一个漫长的过程)。我当前的方法是这样的:
./test.sh >tmp.txt &
PID=$!
tail -f tmp.txt | while read line; do
echo $line
ps ${PID} > /dev/null
if [ $? -ne 0 ]; then
echo "exiting.."
fi
done;
但不幸的是,这将打印“exiting”然后等待,因为 tail -f 仍在运行。我尝试了 break
和 exit
我在 FreeBSD 上运行它,所以我无法使用某些 linux tails 的 --pid=
选项。
我可以使用 ps 和 grep 来获取尾部的 pid 并杀死它,但这对我来说看起来非常难看。
有什么提示吗?
I want to process each stdout-line for a shell, the moment it is created. I want to grab the output of test.sh
(a long process). My current approach is this:
./test.sh >tmp.txt &
PID=$!
tail -f tmp.txt | while read line; do
echo $line
ps ${PID} > /dev/null
if [ $? -ne 0 ]; then
echo "exiting.."
fi
done;
But unfortunately, this will print "exiting" and then wait, as the tail -f is still running. I tried both break
and exit
I run this on FreeBSD, so I cannot use the --pid=
option of some linux tails.
I can use ps
and grep
to get the pid of the tail and kill it, but thats seems very ugly to me.
Any hints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么需要
tail
流程?可以按照 or 的方式做一些事情
如果您想将输出保留在 tmp.txt 中,您
:如果您仍然想使用中间
tail -f
进程,也许您可以使用命名管道(fifo) 而不是常规管道,以允许分离tail
进程并获取其 pid:但是我应该提到,这样的解决方案会带来几个严重的竞争条件问题:
test 的 PID .sh
可以被重用另一个进程;why do you need the
tail
process?Could you instead do something along the lines of
or, if you want to keep the output in tmp.txt :
If you still want to use an intermediate
tail -f
process, maybe you could use a named pipe (fifo) instead of a regular pipe, to allow detaching thetail
process and getting its pid:I should however mention that such a solution presents several heavy problems of race conditions :
test.sh
could be reused by another process;test.sh
process is still alive when you read the last line, you won't have any other occasion to detect its death afterwards and your loop will hang.