| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <assert.h> |
| 8 |
#include <sys/stat.h> |
| 9 |
#include <sys/types.h> |
| 10 |
#include <fcntl.h> |
| 11 |
#include <unistd.h> |
| 12 |
|
| 13 |
/* Return a random integer between MIN and MAX, inclusive. Obtain |
| 14 |
randomness from /dev/random. */ |
| 15 |
|
| 16 |
int random_number (int min, int max) |
| 17 |
{ |
| 18 |
/* Store a file descriptor opened to /dev/random in a static |
| 19 |
variable. That way, we don't need to open the file every time |
| 20 |
this function is called. */ |
| 21 |
static int dev_random_fd = -1; |
| 22 |
|
| 23 |
char* next_random_byte; |
| 24 |
int bytes_to_read; |
| 25 |
unsigned random_value; |
| 26 |
|
| 27 |
/* Make sure MAX is greater than MIN. */ |
| 28 |
assert (max > min); |
| 29 |
|
| 30 |
/* If this is the first time this function is called, open a file |
| 31 |
descriptor to /dev/random. */ |
| 32 |
if (dev_random_fd == -1) { |
| 33 |
dev_random_fd = open ("/dev/random", O_RDONLY); |
| 34 |
assert (dev_random_fd != -1); |
| 35 |
} |
| 36 |
|
| 37 |
/* Read enough random bytes to fill an integer variable. */ |
| 38 |
next_random_byte = (char*) &random_value; |
| 39 |
bytes_to_read = sizeof (random_value); |
| 40 |
/* Loop until we've read enough bytes. Since /dev/random is filled |
| 41 |
from user-generated actions, the read may block, and may only |
| 42 |
return a single random byte at a time. */ |
| 43 |
do { |
| 44 |
int bytes_read; |
| 45 |
bytes_read = read (dev_random_fd, next_random_byte, bytes_to_read); |
| 46 |
bytes_to_read -= bytes_read; |
| 47 |
next_random_byte += bytes_read; |
| 48 |
} while (bytes_to_read > 0); |
| 49 |
|
| 50 |
/* Compute a random number in the correct range. */ |
| 51 |
return min + (random_value % (max - min + 1)); |
| 52 |
} |