如何在命名管道 (mkfifo) 上执行非阻塞 fopen?

发布于 2024-07-13 21:49:14 字数 533 浏览 9 评论 0原文

如果我有一个程序使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你丑哭了我 2024-07-20 21:49:15

您可以open()您的管道O_RDONLY | O_NONBLOCK,如果你想要C流,你可以使用fdopen()来获取。 但是, select() 可能存在问题 - AFAIK,打开用于读取但没有 writer 的管道 fd 始终准备读取,并且 read() 返回0,因此 select() 将无限期地触发。

克服这个问题的一个笨办法是打开管道O_RDWR; 也就是说,至少有一名编写者(您的 C++ 程序)。 无论如何这都会解决你的问题。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文