This is the mail archive of the
gsl-discuss@sources.redhat.com
mailing list for the GSL project.
Re: Random Number Seed
- From: Olaf Lenz <olenz at Physik dot Uni-Bielefeld dot DE>
- To: "Robert G. Brown" <rgb at phy dot duke dot edu>
- Cc: Przemyslaw Sliwa <przemyslaw dot sliwa at db dot com>, gsl-discuss at sources dot redhat dot com
- Date: Mon, 21 Feb 2005 12:55:16 +0100
- Subject: Re: Random Number Seed
- References: <Pine.LNX.4.44.0403011221340.20444-100000@ganesh>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hello!
A few months ago, you suggested the following code snippet for seeding
the RNG from /dev/random:
- -------------------------------------------------
#include <stdio.h>
#include <sys/time.h>
unsigned long int random_seed()
{
~ unsigned int seed;
~ struct timeval tv;
~ FILE *devrandom;
~ if ((devrandom = fopen("/dev/random","r")) == NULL) {
~ gettimeofday(&tv,0);
~ seed = tv.tv_sec + tv.tv_usec;
~ if(verbose == D_SEED) printf("Got seed %u from gettimeofday()\n",seed);
~ } else {
~ fread(&seed,sizeof(seed),1,devrandom);
~ if(verbose == D_SEED) printf("Got seed %u from /dev/random\n",seed);
~ fclose(devrandom);
~ }
~ return(seed);
}
- -------------------------------------------------
I've used the code for quite a while now and only today I noticed a big
problem with it. The code tests, if /dev/random can be opened, but it
does NOT test if the fread has actually read any number.
In my case, this resulted in the fact that the seed was not seeded at
all and all processes used the same seed.... P-(
So to all who have been using the code, I would recommend to check their
results. For the future, I would recommend to use the following code:
- -------------------------------------------------
#include <stdio.h>
#include <sys/time.h>
unsigned long int random_seed()
{
~ unsigned int seed;
~ struct timeval tv;
~ FILE *devrandom;
~ if ((devrandom = fopen("/dev/random","r")) == NULL) {
~ gettimeofday(&tv,0);
~ seed = tv.tv_sec + tv.tv_usec;
~ if(verbose == D_SEED) printf("Got seed %u from gettimeofday()\n",seed);
~ } else {
~ if (fread(&seed,sizeof(seed),1,devrandom) == 1) {
~ if(verbose == D_SEED) printf("Got seed %u from /dev/random\n",seed);
~ fclose(devrandom);
~ } else {
~ gettimeofday(&tv,0);
~ seed = tv.tv_sec + tv.tv_usec;
~ if(verbose == D_SEED) printf("Got seed %u from
gettimeofday()\n",seed);
~ }
~ }
~ return(seed);
}
- -------------------------------------------------
Cheers
Olaf
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFCGcwjtQ3riQ3oo/oRAsjeAKC3CIz3kxxt/ZJUiuYzemIU1IqVdgCffoYW
vXr8SEcXH69ulMzTfBwWuHw=
=2RKb
-----END PGP SIGNATURE-----