Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5042

C/C++ • Re: C++ fgets behaving very oddly on Bookworm (no other environment tested yet)

$
0
0
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.
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.

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;}
And replace the "writer" with the command

Code:

# cat > /tmp/my_named_pipe
and start typing lines of text, you will see that fgets will block until a new line of text is entered. The "reader" will only exit once the cat command exits. You can either kill it using ctrl-c or send the eof marked usinng ctrl-d.

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



Viewing all articles
Browse latest Browse all 5042

Trending Articles