Generating Random Numbers

By Danny Kalev, ITworld |  How-to

This week, I will show how to generate random numbers. First, we will
learn how to use the standard library's routines, and then we will
focus on a Linux-specific technique.

ANSI C defines two functions, rand() and srand(), for generating random
integral values. These functions are declared in the header file
as follows:

int rand();
void srand(unsigned int seed);

Each invocation of rand() returns a pseudo-random number -- pseudo-
random because rand() produces the same sequence of numbers every time
you run the program. To produce a different sequence on every
execution, set a unique seed value by calling srand() before the first
rand() call. It's customary to pass the current system time as an
argument to srand(). So that forked processes or different instances of
the same program that start in the same second generate unique random
values, add the current process ID to the time argument:

#include
#include
#include
int main()
{
int n;
srand(time(NULL) + getpid())
for(n=0; n<100; ++n)
printf(" %d ",rand());/*print 100 random numbers*/
}

rand() guarantees that the generated numbers are relatively well
distributed within the valid ranges. Thus, it can be used in game
programming or protocols that insert random delays. Another advantage
is its ability to reproduce a sequence (for example, when you debug a
program) by providing the same seed value to srand().

Entropy Pool
Certain applications, encryption algorithms for instance, require non-
reproducible sequences of random values. Linux stores timings of
external events such as mouse movements and key presses, and extracts
information from these events. The results are stored in an entropy
pool. If you need random numbers based on unpredictable events, you can
read from one of two devices, namely /dev/random and /dev/urandom.
The /dev/random device will return as many bytes as the device assumes
exist in the entropy pool. The device /dev/urandom generates as many
random numbers as you need, based on the current entropy pool. The
values returned from these devices are the result of applying a hash
algorithm to the entropy pool. You can find more documentation on the
entropy pool, the random devices and their usage in the random driver
source file drivers/char/random.c

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Ask a Question
randomness