C++ FIFO 奇怪的行为

标签 c++ linux fifo

我正在为 IPC 使用 FIFO。然而,他们执行一些奇怪的行为。 至于演示,我在这里发布了一些可以编译和运行的代码。 附加信息,我在 Linux Ubuntu 上,带有基本的 g++ 编译器,没什么特别的。

#include <iostream>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <iostream>
using namespace std;

int main() {

    cout << "START" << endl;

    int fifo;
    int code;
    mkfifo("/tmp/FIFO", 666);
    if ((fifo = open("/tmp/FIFO", O_RDONLY | O_NONBLOCK)) < 0) {
        perror("open failed");
    }
    else {
        cout << "open successed" << endl;
        code = close(fifo);
        cout << "close: " << code << endl;
        if ((fifo = open("/tmp/FIFO", O_WRONLY | O_NONBLOCK)) < 0) {
            perror("reopen failed");
        }
        else {
            cout << "reopen successed" << endl;
            code = close(fifo);
            cout << "close: " << code << endl;
        }
    }

    cout << "END" << endl;
    return 0;
}

我对输出的期望是这样的,因为我成功关闭了它:

START
open successed
close: 0
reopen successed
close: 0
END

但是,我明白了,第二次打开失败了。为什么?为什么会出现这种愚蠢的错误消息?

START
open successed
close: 0
reopen failed: No such device or address
END

我真的很想重新打开 FIFO 进行写入。我想知道上面的代码不起作用的原因。

最佳答案

从重新打开中删除 O_NONBLOCK 标志,或者如果您想保留该标志,请连接到已打开以供读取的 fifo。 这是正确的行为。

http://linux.die.net/man/7/fifo

A process can open a FIFO in nonblocking mode. In this case, opening for read only will >succeed even if no-one has opened on the write side yet, opening for write only will fail >with ENXIO (no such device or address) unless the other end has already been opened.

关于C++ FIFO 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11353026/

相关文章:

c++ - Qt 应用程序性能与 WinAPI/MFC/WTL/

c++ - 类继承/组合的设计

linux - 为什么我的脚本上多了一个 0

c - 为什么在等待条件变量时需要 while 循环

amazon-web-services - 如何搜索/查询符合条件的SQS队列元素

c - 我想用管道和信号制作一个 REPL 风格的程序,但是我的程序锁定了

Python 和 FIFO

c++ - `enable_if()` 禁用模板类的静态成员函数声明

c++ - 检查 std::vector 中的字符串是否包含 C++ 中的子字符串

linux - 仅使用 smbclient 获取文件夹