如何在命名管道 (mkfifo) 上执行非阻塞 fopen?
如果我有一个程序使用 mkfifo 创建并尝试打开命名管道,如何在不阻塞的情况下打开管道进行读取或写入?
具体来说,我正在编写一个 C 程序,无论有没有 gui(用 Java 编写)都可以运行。
在 C 程序中,我使用 mkfifo 成功创建了命名管道,但是当我这样做时,
FILE* in = fopen(PIPE_IN, "r"); /* Where PIPE_IN is the filename*/
fopen 不会返回,直到 GUI 打开该管道进行写入。 我想做的是让该管道准备好被读取一次(如果)GUI 决定写入它 - 我将把文件描述符放在 select() 调用中。 可以合理地预期 java GUI 可能永远不会真正启动,因此我不能依赖它在任何特定点甚至根本不打开管道的另一端。
我还将打开第二个管道进行写入,我想我也会遇到同样的问题。 此外,我无法在没有读取器的输出管道上设置 O_NONBLOCK 。
有什么建议么?
(这是在linux系统上运行的)
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?
Specifically, I'm writing a C program which can be run with or without a gui (written in Java).
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 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.
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.
Any suggestions?
(This is running on a linux system)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以
open()
您的管道O_RDONLY | O_NONBLOCK
,如果你想要C流,你可以使用fdopen()
来获取。 但是,select()
可能存在问题 - AFAIK,打开用于读取但没有 writer 的管道 fd 始终准备读取,并且read()
返回0,因此select()
将无限期地触发。克服这个问题的一个笨办法是打开管道
O_RDWR
; 也就是说,至少有一名编写者(您的 C++ 程序)。 无论如何这都会解决你的问题。You could
open()
your pipeO_RDONLY | O_NONBLOCK
, and if you want the C stream, you can get it withfdopen()
. However, there might be a problem with theselect()
- AFAIK, a pipe fd open for reading that has no writer is always prepared for reading, andread()
returns 0, so theselect()
would fire indefinitely.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.