I would be interested to know where you read that. I don't believe this to be the case. A simple experiment will show this.My reading of the documentation is that NULL is returned on the call to fgets if the FIFO is empty, whether or not the writer has closed the FIFO, and this is not classed as an error. Maybe that's just semantics, because what matters is that fgets returns a NULL. Which leads us to this:So each time the writer opens the FIFO, the reader will open it for reading, and will keep reading from the FIFO until fgets returns a NULL. At this point the reader should close the FIFO and try again.
If you run the following "reader" code in one terminal
Code:
#include <cstdio>#include <cstring>#include <iostream>int main(){ FILE *fp = fopen("/tmp/my_named_pipe", "r"); if (fp) { char msgbuf[1024]; while (fgets(msgbuf, sizeof(msgbuf), fp)) { printf("Received %s", msgbuf); } fclose(fp); } return 0;}
Code:
# cat > /tmp/my_named_pipe
The "reader" code above will block in fopen until there is a "writer" on the FIFO, and fgets will block waiting for input from the FIFO, and will return NULL once the "writer" has exited. That is why there is a need for a loop and the fclose and then fopen. You want to block in fopen until there is a "writer" for the FIFO.
Statistics: Posted by AndyD — Sun Feb 11, 2024 8:35 pm