I am trying to gather true random numbers from /dev/random. Here is my simple code:
u_char buf[256];
memset(buf, 0, 256);
int dev = open("/dev/random", O_RDONLY);
int nbr = read(dev, buf, 100);
printf("Number of bytes returned : %d\n", nbr);
As you can see that i am asking for 100 random bytes but when i run this program i always get output in variable nbr in range of 15 to 30 which is understandable as /dev/random does not always have enough entropy but my expectation was that upon read(), /dev/random should block until it fills my buffer to 100 random bytes which does not occur in this case and program does not block. I read man pages for /dev/random. It says that
When the entropy pool is empty, reads from /dev/random will block
until additional environmental noise is gathered.
Does this literally mean that /dev/random will only block when entropy pool is empty and will not block when it has any amount data whether or not it is less than the required bytes?
Any help would be appreciated.
That’s not special to
/dev/random, that’s just the behaviour ofread. The parameter is a buffer size andreadwill return what’s available up to that size.Consider using a
FILE*andfreadinstead to read one block of 100 bytes.