Bash:在读取/写入命名管道时替代 cat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11291465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: Alternative to cat in reading/writing to named pipe
提问by hexacyanide
I am starting a process, and redirecting its output to a named pipe. I'm reattaching to the named pipe with with cat > $pipe. How do I set the named pipe to die when the process' stdout dies without polling for the parent process' death?
我正在启动一个进程,并将其输出重定向到命名管道。我正在使用cat > $pipe. 当进程的标准输出死亡而不轮询父进程的死亡时,如何将命名管道设置为死亡?
Aside from that, what else besides catcan be used to open named pipes?
除此之外,还有什么cat可以用来打开命名管道?
回答by c00kiemon5ter
a fifo is always readyto read and write, so a program like catand tail -fwill not stop reading, ever. What you want to check is whether there's a process that writes to that file, and if there is no such process, stop reading. (btw, the best way to read a file, is to readit.)
fifo 总是准备好读取和写入,因此程序喜欢cat并且tail -f永远不会停止读取。您要检查的是是否有写入该文件的进程,如果没有该进程,则停止读取。(顺便说一句,读取文件的最佳方式就是使用read它。)
lsofcan tell you who reads and writes from/to a specified file. Look in its man page, and try something like:
lsof可以告诉您谁从/向指定文件读取和写入。查看其手册页,然后尝试以下操作:
while lsof /path/to/fifo
do
read -r line < /path/to/fifo
printf "%s\n" "$line"
done
I am not sure, and do not have the time to look into lsof, to find out which option outputs only processes that writeto that file. Please look into that on the man page.
So, as long as there is a process that writes to the fifo, this scripts read a line and prints it. Once there is no process writting to the file, the loop breaks and the script exits.
我不确定,也没有时间查看 lsof,找出哪个选项只输出写入该文件的进程。请查看手册页上的内容。
所以,只要有一个进程写入fifo,这个脚本就会读取一行并打印出来。一旦没有进程写入文件,循环就会中断并且脚本退出。
I do not know of another way to check whether there is a process writing to a file other than using lsof. If anyone does know a more standard way, I would like to know too.
我不知道除使用lsof. 如果有人知道更标准的方式,我也想知道。
回答by Wernsey
cat > $pipewrites to the pipe, not read from it.
cat > $pipe写入管道,而不是从中读取。
If you want to read data from the pipe and print it on the terminal try tail -f $pipe.
如果您想从管道读取数据并在终端上打印,请尝试tail -f $pipe.
The -foption keeps tailrunning and have it print output when new data is written to the pipe.
该-f选项保持tail运行并在新数据写入管道时打印输出。
See also this articlefrom Linux Journal.
另请参阅Linux Journal 上的这篇文章。

![bash grep 区分大小写 [AZ]?](/res/img/loading.gif)