我正在为 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/