From 93b2f4164aac8ef87ed8eee17554aa1565ea5528 Mon Sep 17 00:00:00 2001 From: Bill Somerville Date: Fri, 18 Dec 2015 17:32:56 +0000 Subject: [PATCH] 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 --- lib/init_random_seed.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/init_random_seed.c b/lib/init_random_seed.c index 4be42d044..7e6ed889c 100644 --- a/lib/init_random_seed.c +++ b/lib/init_random_seed.c @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include /* 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);