How to flush a pipe using bash

[亡魂溺海] 提交于 2019-12-18 15:03:28

问题


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?


回答1:


I think dd is your friend:

dd if=myfifo iflag=nonblock of=/dev/null

strace shows

open("myfifo", O_RDONLY|O_NONBLOCK)

and indeed doesn't even block on an empty fifo.




回答2:


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.




回答3:


Try this:

"Opening the FD read/write rather than read-only when setting up the pipeline prevents blocking."

from:

Setting up pipelines reading from named pipes without blocking in bash



来源:https://stackoverflow.com/questions/3348614/how-to-flush-a-pipe-using-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!