fread() 从基于管道的描述符读取设置错误,而不是没有数据的 EOF
我需要使用 fread() 从管道的读取端读取内容。
但是,虽然我希望 fread() 在管道中没有任何内容时设置 EOF,但它却设置错误指示器。我检查了 posix 和 C 标准,但没有发现任何线索。也许我正在做一些无意的事情(读起来,愚蠢的),对吧:)
这是摘录:
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您使用的是非阻塞管道,我相信您会得到:
errno==EAGAIN
当根本没有任何内容可供读取时(意味着现在没有任何内容,但也许以后会发生一些事情 - 尝试(e )稍后再说)。EOF
当管道的写入端关闭时(意味着没有更多数据传入)。请参阅
read()
的联机帮助页,了解设置 O_NONBLOCK 模式时 read() 的行为。fread()
行为应该与 read() 一致。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().