I'm trying to communicate two processes via Named pipes but I'm having problems with the reader process. The idea is that the consumer reads several messages that the producer writes into the pipe in random periods. Since these periods can be long, the consumer should block in the read operation until the producer has written the message into the pipe.
This is the code that I have now.
FILE* result_pipe_stream;
...
result_pipe_stream = fopen(result_pipe , "r");
...
string read_result_from_pipe(){
if (result_pipe_stream == NULL){
return NULL;
}
char buf[BUFSIZ];
std::stringstream oss;
while (1) {
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) {
int buflen = strlen(buf);
if (buflen >0){
if (buf[buflen-1] == '\n'){
buf[buflen-1] = '\0';
oss << buf;
return oss.str();
} else {
oss << buf;
}
}
} else {
// Necessary to avoid that fgets return NULL after closing the pipe for the first time.
clearerr(result_pipe_stream);
}
}
}
The first time the consumer reads from the pipe, the method works properly. It awaits until the writer sends a message and returns the value. However, from that point on, when the method is called again the fgets
returns NULL
until the writer adds the new message.
What is missing for the consumer to block after the second read?
The producers is a Java application writing the pipe like this
try {
OutputStream output = new FileOutputStream(writePipe, true);
output.write(taskCMD.getBytes());
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}