I use read (2) to read from a file ( /dev/random , where data comes in very slowly).
However, read () returns only a few bytes after reading, while I would like it to wait for the specified number of bytes to be read (or an error occurred), so the return value should always be considered, or -1.
Is there any way to enable this behavior? The open (2) and read (2) commands do not contain any useful information on this topic, and I did not find any information about the topic on the Internet.
I am fully aware of the workaround by simply placing read() inside the while loop and calling it until all the data has been read. I just would like to know if this can be achieved appropriately, which gives deterministic behavior and includes only O (1) syscalls instead of non-deterministic O (n) in case of solving the while loop.
The following minimal example reproduces the problem.
#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); }
mic_e source share