我正在使用read(2)
来从一个文件(/dev/random
, 数据到达非常缓慢)读取内容。
然而,read()
只能读取很少的字节就返回了,但我希望它等到读取完指定数量的字节或出现错误后再返回,所以返回值应该始终为计数,否则为-1。
有没有办法启用这种行为?open(2)
和read(2)
的手册在这方面没有任何有用的信息,也没有在网上找到有关此主题的信息。
我完全意识到将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);
}
/dev/random
,多进行几次读取调用也不会拖慢你的速度。 - FatalError