问题描述
如果我有一个计划,创建并尝试使用mkfifo子打开一个命名管道,我怎么能打开读或写一个管道无堵塞?
If I have a program which creates and attempts to open a named pipe using mkfifo, how can I open a pipe for reading or writing without blocking?
具体来说,我正在写,可以带或不带图形用户界面(Java编写的)运行的C程序。
Specifically, I'm writing a C program which can be run with or without a gui (written in Java).
在C程序中,我使用mkfifo子成功地创建命名管道,但是当我做
In the C program, I successfully create the named pipes using mkfifo, however when I do
FILE* in = fopen(PIPE_IN, "r"); /* Where PIPE_IN is the filename*/
的fopen不返回,直到GUI打开该管道进行写入。我希望做的是有该管道准备好被读取一次(如果)在GUI决定写信给它 - 我将放在文件描述符在select()调用。这是合理的期望,在Java GUI可从来没有真正启动,所以我不能依靠它来打开管道的另一端在任何特定点,甚至都没有。
fopen doesn't return until the GUI opens that pipe for writing. What I wish to do is have that pipe ready to be read once (if) the GUI decides to write to it - I'll be putting the file descriptor in a select() call. It's reasonable to expect that the java GUI may never actually be started, so I cannot rely on it to open the other end of the pipe at any specific point or even at all.
我也将有第二个开放的管道用于写作,我想我也会有同样的问题。此外,我不能在没有读者的输出管道设置O_NONBLOCK。
I will also have a second pipe open for writing, and I assume I will have the same problem. Further, I can't set O_NONBLOCK on an output pipe that has no reader.
有什么建议?
(这是一个Linux系统上运行)
(This is running on a linux system)
推荐答案
您可以的open()
你管 O_RDONLY | O_NONBLOCK
,如果你想的C流,你可以用 fdopen得到它()
。但是,有可能是与选择()
一个问题 - ppared阅读AFAIK,管道的fd开放读一个没有作家永远是$ P $和阅读()
返回0,因此选择()
将无限期开火。
You could open()
your pipe O_RDONLY | O_NONBLOCK
, and if you want the C stream, you can get it with fdopen()
. However, there might be a problem with the select()
- AFAIK, a pipe fd open for reading that has no writer is always prepared for reading, and read()
returns 0, so the select()
would fire indefinitely.
克服这将是打开管道的一个缺憾方式 O_RDWR
;也就是说,至少有一位作家(您的C ++程序)。这将反正您解决问题。
A kludgy way of overcoming this would be to open the pipe O_RDWR
; that is, have at least one writer (your C++ program). Which would solve your problem anyway.
这篇关于我如何在一个命名管道(mkfifo子)执行非阻塞的fopen?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!