如何使用 bash 冲洗管道
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3348614/
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
How to flush a pipe using bash
提问by User1
I have a script that writes to a named pipe and another that reads from the pipe. Occasionally, when starting the script I have noticed that the contents of the pipe exist from a previous run of the script. Is there a way to flush out the pipe at the beginning of the script?
我有一个写入命名管道的脚本和另一个从管道读取的脚本。有时,在启动脚本时,我注意到管道的内容存在于脚本的先前运行中。有没有办法在脚本的开头冲洗管道?
采纳答案by mvds
I think ddis your friend:
我想dd是你的朋友:
dd if=myfifo iflag=nonblock of=/dev/null
strace shows
strace 显示
open("myfifo", O_RDONLY|O_NONBLOCK)
and indeed doesn't even block on an empty fifo.
并且确实甚至不会阻塞空的先进先出。
回答by fooit
Try this:
尝试这个:
"Opening the FD read/write rather than read-only when setting up the pipeline prevents blocking."
“在设置管道时打开 FD 读/写而不是只读可以防止阻塞。”
from:
从:
Setting up pipelines reading from named pipes without blocking in bash
回答by Borealid
You can read from the pipe until it is empty. This will effectively flush it.
您可以从管道中读取,直到它为空。这将有效地冲洗它。
Before you attempt this daring feat, call fcntl(mypipe, F_SETFL, O_NONBLOCK)(I don't know the shell-scripting equivalent) to make a read when the pipe is empty not hang your program.
在您尝试这个大胆的壮举之前,请调用fcntl(mypipe, F_SETFL, O_NONBLOCK)(我不知道等效的 shell 脚本)在管道为空时读取而不是挂起您的程序。

