问题
After opening the file descriptor fd
and other sanity checks for /dev/random, I am attempting to read how many bytes are readable from the device so I can pull this amount if it is required by my program.
My basic code is this:
if (fd = open("/dev/random", O_RDONLY) < 0) {
perror("open");
return 1;
}
...
if(ioctl(fd, FIONREAD, &n) < 0) { //file descriptor, call, unsigned int
perror("ioctl");
return 1;
}
printf("%d bytes available for reading.\n", n);
return 0;
No matter what the scenario (as root or normal user in case that was required) it always return 0 bytes available to be read.
I have been suggested before that this is a method to retrieve what I can take out of the device, do you know what possible problems or faults in my program cause it to always return zero? Do you know of any other methods to do what I am wishing to do?
回答1:
Which Linux version are you using? On 2.6.32 your program outputs
ioctl: Invalid argument
FWIW, the documentation I've been able to find wrt the FIONREAD ioctl says that it's for sockets, pipes, FIFOs, and tty's. /dev/random, OTOH, is a character special file, so combined with the "invalid argument" errno I'd say FIONREAD is not supported for /dev/random.
And no, I don't know of any simple built-in way to figure out the number of available bytes in /dev/random. One thing which might work would be to have a separate thread reading data from /dev/random and putting it into a thread-safe queue, then have a way to check whether the queue is empty in a non-blocking way (say, built around pthread_mutex_trylock()).
来源:https://stackoverflow.com/questions/5535030/linux-ioctl-fionread-returning-0-bytes-available-at-dev-random