tags:

views:

617

answers:

3

I want to use /dev/random or /dev/urandom in C - how can i do it ? I don't know how can i handle them in C, if someone knows please tell me how. Thank you.

+6  A: 

It's simple: they're just like files. You read from them and you get random data.

int randomData = open("/dev/random", O_RDONLY);
int myRandomInteger;
read(randomData, &myRandomInteger, sizeof myRandomInteger);
// you now have a random integer!
close(randomData);

You may read many more random bytes before closing the file descriptor.

The difference between /dev/random and /dev/urandom is that /dev/random provides a limited (but relatively large) number of random bytes, and will block waiting that the kernel gives some more if the buffer is outrun, while /dev/urandom will always provide random bytes though they may become of a lesser quality once the initial buffer is outrun. See man 4 random for more information.

zneak
okay, nice answer. And what if I want to set it to read multiple numbers ? Would i do while(something) { read(..) } or should i open/close it everytime the loop starts over ?
stojance
Yup, you would read several times. I'll edit my answer.
zneak
Or just read more to fill an array of integers.
mark4o
+4  A: 

Just open the file for reading and then read data. In C++0x you may wish to use std::random_device which provides cross-platform access to such devices.

Tronic
A: 

Zneak is 100% correct. Its also very common to read a buffer of random numbers that is slightly larger than what you'll need on startup. You can then populate an array in memory, or write them to your own file for later re-use.

A typical implementation of the above:

typedef struct prandom {
     struct prandom *prev;
     int64_t number;
     struct prandom *next;
} prandom_t;

This becomes more or less like a tape that just advances which can be magically replenished by another thread as needed. There are a lot of services that provide large file dumps of nothing but random numbers that are generated with much stronger generators such as:

  • Radioactive decay
  • Optical behavior (photons hitting a semi transparent mirror)
  • Atmospheric noise (not as strong as the above)
  • Farms of intoxicated monkeys typing on keyboards and moving mice (kidding)

Not being concerned with quality, if you need a lot of numbers for something like a monte carlo simulation, its much better to have them available in a way that will not cause read() to block.

However, remember, the randomness of a number is as deterministic as the complexity involved in generating it. /dev/random and /dev/urandom are convenient, but not as strong as using a HRNG (or downloading a large dump from a HRNG).

Tim Post