关于基于管道从描述符读取c:fread()会设置错误,而不是没有数据的EOF

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

我需要使用fread()从管道的读取端读取内容。

但是,尽管我期望当管道中没有任何内容时,fread()会设置EOF,但它会设置错误指示符。 我检查了posix和C标准,发现那里没有任何线索。 可能我在做意外的事情(读,傻),对:)

这是摘录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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, ferror(f), feof(f));

   return 0;
}

由于您使用的是非阻塞管道,因此我相信您会得到:

  • errno==EAGAIN当根本没有什么要阅读时(现在什么也没有了,但也许以后再说-再试一次(e))。
  • EOF当管道的写侧关闭时(意味着不再有数据来)。

有关设置O_NONBLOCK模式时read()的行为,请参见read()的手册页。 fread()行为应与read()一致。