This is the mail archive of the gsl-discuss@sources.redhat.com mailing list for the GSL project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Random Number Seed


-----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-----


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]