I’m using FIFO for IPC. However they perform some strange behaviour.
As for demostration I post some code here which can be compiled and runned.
Additional info, I’m on Linux Ubuntu, with the basic g++ compiler comes with it, nothing special.
#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;
}
My expectation about the output is something like this, since I close it successfully:
START
open successed
close: 0
reopen successed
close: 0
END
However, I got this, the second open fails. Why? And why with this silly error message?
START
open successed
close: 0
reopen failed: No such device or address
END
I really would like to reopen the FIFO for write. And I’d like know the reason why the code above doesn’t work.
Remove the O_NONBLOCK flag from reopen or if you want to keep the flag, connect to a fifo that is already open for reading.
It is the correct behavior.
http://linux.die.net/man/7/fifo