我正在使用read (2)
從文件(/dev/random
,其中數據到達非常緩慢)進行讀取。禁止Linux讀取(2),直到所有計數字節到達
但是,read()僅在讀取幾個字節後返回,而我希望它等到指定的字節數已被讀取(或發生錯誤),因此返回值應始終爲count ,或-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);
}
+1,因爲這是'/ dev/random'反正...一些額外的讀取電話不會減慢任何。 – FatalError