【发布时间】:2012-09-20 08:43:57
【问题描述】:
我正在使用read (2) 从文件中读取数据(/dev/random,其中数据到达非常缓慢)。
但是,read() 仅在读取几个字节后返回,而我希望它等待直到读取指定数量的字节(或发生错误),因此返回值应始终为 count,或 -1。
有没有办法启用这种行为? open (2) 和 read (2) 联机帮助页不包含有关该主题的任何有用信息,我也没有在 Internet 上找到有关该主题的任何信息。
我完全了解将read() 放入while 循环并调用它直到读取所有数据的解决方法。我只想知道这是否可以通过产生确定性行为并且仅涉及 O(1) 系统调用的适当方式来实现,而不是在 while 循环解决方案的情况下使用非确定性 O(n)。
以下最小示例重现了该问题。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int fd = open("/dev/random", 0);
char buf[128];
size_t bytes = read(fd, buf, sizeof(buf));
printf("Bytes read: %lu\n", bytes); //output is random, usually 8.
close(fd);
}
【问题讨论】:
标签: c linux file system-calls blocking