Linux: ioctl/FIONREAD returning 0 bytes available at /dev/random?

谁说我不能喝 提交于 2019-12-11 09:03:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!