如何创建一个不会阻止写入器和读取器的 linux fifo“管道”(或其他东西)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7646592/
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 create a linux fifo "pipe" (or something), which does not block writer and reader?
提问by bpgergo
I created a fifo pipe
我创建了一个fifo管道
$ mkfifo pipename
Now if I write somthing into it, the command won't not return,
现在如果我往里面写一些东西,命令不会不返回,
$ echo "foo" > pipename
until I read it:
直到我读到:
$ cat < pipename
foo
Also, also read command won't return until something is written to it.
此外,在写入某些内容之前,读取命令也不会返回。
Now, I would like to create a such a thing (actually, maybe this thing should not be considered to be a pipe, rather some sort of buffer) that
现在,我想创建一个这样的东西(实际上,也许这个东西不应该被认为是管道,而是某种缓冲区)
- reading command will return immediately, regardless of there is something in the pipe or not (if pipe is empty, then reading should return immediately with zero bytes)
- write command returns immediately
- 读取命令将立即返回,无论管道中是否有东西(如果管道为空,则读取应立即返回零字节)
- 写命令立即返回
Thanks
谢谢
采纳答案by William Pursell
Use a fifo, but write your own reader and writer. Open the fifo with O_NONBLOCK set, and open will return immediately if no other process has the other side open. Your write command will return immediately (as requested), but the data will be lost. If you want the data to persist, use a regular file.
使用先进先出,但写你自己的读者和作家。打开设置了O_NONBLOCK的fifo,如果没有其他进程打开另一端,open将立即返回。您的写入命令将立即返回(根据要求),但数据将丢失。如果您希望数据持久化,请使用常规文件。