I'm attempting to write interprocess communication for the following scenario:
- A "reader" (the program I am writing) listens continuously on a fifo.
- Writers appear and disappear in serial, like running
echo "[string]" > fifo_inrepeatedly.
Here is the reader logic I am using (as far as I know). The executable should be run from a directory containing mkfifo the_fifo:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
int fd = open("the_fifo", O_RDONLY | O_NONBLOCK);
char buf[32];
std::string line = "";
while(1) {
ssize_t n_read = read(fd, buf, sizeof buf);
if(n_read > 0) line.append(buf, n_read);
std::cout << line;
std::cout.flush();
line = "";
}
return 0;
}
This executable should print characters as they are written into the_fifo.
Occasionally when one runs echo "[string]" > fifo_in somewhere else on the system while this executable is running, the executable does not print the string.
What is going wrong?