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

纵然是瞬间 提交于 2019-12-14 01:24:19

问题


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 sets 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;
}

回答1:


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().



来源:https://stackoverflow.com/questions/4377210/fread-reading-from-a-descriptor-based-on-a-pipe-sets-error-not-eof-where-ther

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!