开发者

fread() reading from a descriptor based on a pipe sets error, not EOF where there is no data

开发者 https://www.devze.com 2023-01-29 01:55 出处:网络
I need to read with fread() the stuff from the read end of the pipe. But while i expect the fread() to set EOF when there is nothing in the pipe, it instead se开发者_运维技巧ts the error indicator. I

I need to read with fread() the stuff from the read end of the pipe.

But while i expect the fread() to set EOF when there is nothing in the pipe, it instead se开发者_运维技巧ts the error indicator. I have checked the posix and C standards and found no clue there. Probably i'm doing something unintended (read, silly), right:)

Here's the excerpt:

#include <stdio.h>
#include <fcntl.h>

int main()
{
   char buf[128];
   FILE *f;
   int pipe_fd[2], n;

   pipe(pipe_fd);
   fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK);

   f=fdopen(pipe_fd[0], "r");
   n=fread(buf, 1, 1, f);
   printf("read: %d, Error: %d, EOF: %d\n", n, ferror(f), feof(f));

   return 0;
}


Since you're using a non-blocking pipe, I believe you would get:

  • errno==EAGAIN when there simply isn't anything there to read (meaning nothing now but maybe something later - try (e)again later).
  • EOF when the writing side of the pipe is closed (meaning no more data is coming).

See the manpage for read() about how read() behaves when O_NONBLOCK mode is set. fread() behavior should be consistent with read().

0

精彩评论

暂无评论...
验证码 换一张
取 消