Improve the randomness of the srand seed generator

XOR:ing the time since epoch in seconds with the PID fails for processes
started every second since the PID and time increment in step regularly in
this scenario and therefore give identical seeds. Thanks to Steve K9AN for
spotting this subtle flaw.

git-svn-id: svn+ssh://svn.code.sf.net/p/wsjt/wsjt/branches/wsjtx@6294 ab8295b8-cf94-4d9e-aec4-7959e3be5d79
This commit is contained in:
Bill Somerville 2015-12-18 17:32:56 +00:00
parent 906b2dba89
commit 93b2f4164a
1 changed files with 9 additions and 3 deletions

View File

@ -4,7 +4,7 @@
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
/* basic PRNG to use for improving the basic seed selection */
@ -48,8 +48,14 @@ void init_random_seed(void)
}
if (!have_seed)
{
// fallback to XOR:ing the time and pid
seed = time (NULL) ^ getpid ();
// fallback to combining the time and PID in a fairly random way
pid_t pid = getpid ();
struct timeval tv;
gettimeofday (&tv, NULL);
seed = (unsigned)(((unsigned)pid << 16)
^ (unsigned)pid
^ (unsigned)tv.tv_sec
^ (unsigned)tv.tv_usec);
seed = lcg (seed);
}
srand (seed);