I have two separate programs in C++, one that writes to two named pipes in unpredictable intervals and one that should wait to read new content from the pipes whenever available. For simplicity, here my writer only writes two times to the pipes (1st: "One" "Tree" , 2nd: "Two" "Fogs").
My writer program is:
#include <unistd.h>
#include <iostream>
int main()
{
int fd1, fd2;
const char* myfifo1 = "/tmp/myfifo1";
const char* myfifo2 = "/tmp/myfifo2";
mkfifo(myfifo1, 0666);
mkfifo(myfifo2, 0666);
fd1 = open(myfifo1, O_WRONLY);
fd2 = open(myfifo2, O_WRONLY);
write(fd1, "One", sizeof("One"));
write(fd2, "Tree", sizeof("Tree"));
sleep(5);
write(fd1, "Two", sizeof("Two"));
write(fd2, "Fogs", sizeof("Fogs"));
close(fd1);
close(fd2);
unlink(myfifo1);
unlink(myfifo2);
}
My reader program is:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd1, fd2;
const char * myfifo1 = "/tmp/myfifo1";
const char * myfifo2 = "/tmp/myfifo2";
char buf1[MAX_BUF], buf2[MAX_BUF];
fd1 = open(myfifo1, O_RDONLY);
fd2 = open(myfifo2, O_RDONLY);
while (1) {
read(fd1, buf1, MAX_BUF);
read(fd2, buf2, MAX_BUF);
printf("Received: %s\n", buf1);
printf("Received: %s\n", buf2);
}
close(fd1);
close(fd2);
return 0;
}
I do not want the reader to terminate or close the connection between the reads, I need it to remain active and wait until the writer writes something new in the named pipe. However, by simultaneously running these two programs (in different cores, first the writer and then the reader) I get:
Received: One
Received: Tree
Received: Two
Received: Fogs
Received: Two
Received: Fogs
Received: Two
Received: Fogs
Received: Two
Received: Fogs
...
...
The wanted behavior would be:
Received: One
Received: Tree
Received: Two
Received: Fogs
and then nothing (the reader should wait for another write).
I understand that I should somehow clear the buffer after I read it, but isn't it the default behavior of read? Since it finished reading "Two" (and also "Fogs"), why does it keep reading it and does not wait for new content?
What modifications should I make?
Thank you very much in advance!