Shell 杀死管道进程的好方法?
我想在创建shell时处理shell的每个标准输出行。我想获取Shell 杀死管道进程的好方法?,shell,process,pid,tail,sh,Shell,Process,Pid,Tail,Sh,我想在创建shell时处理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; 但不幸的是,这将打印“退出”,然后等
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;
但不幸的是,这将打印“退出”,然后等待,因为tail-f仍在运行。我尝试了中断
和退出
我在FreeBSD上运行它,因此无法使用某些linux尾部的--pid=
选项
我可以使用ps
和grep
来获取尾巴的pid并杀死它,但这对我来说非常难看
有什么提示吗?为什么需要tail
过程
你能不能改为按照
./test.sh | while read line; do
# process $line
done
或者,如果要将输出保留在tmp.txt中:
./test.sh | tee tmp.txt | while read line; do
# process $line
done
如果仍要使用中间tail-f
进程,可能可以使用命名管道(fifo)而不是常规管道,以允许分离tail
进程并获取其pid:
./test.sh >tmp.txt &
PID=$!
mkfifo tmp.fifo
tail -f tmp.txt >tmp.fifo &
PID_OF_TAIL=$!
while read line; do
# process $line
kill -0 ${PID} >/dev/null || kill ${PID_OF_TAIL}
done <tmp.fifo
rm tmp.fifo
/test.sh>tmp.txt&
PID=$!
mkfifotmp.fifo
tail-f tmp.txt>tmp.fifo&
PID_OF_TAIL=$!
读行时;做
#进程$行
kill-0${PID}>/dev/null | | kill${PID_OF_TAIL}
我现在觉得自己真的很愚蠢,因为第一个解决方案显然有效。我对shell脚本比较陌生,没有意识到您提到的第一个解决方案不会阻止。。谢谢