From 75d97ca45b74eccc01b18f44040f946d9d5df9f5 Mon Sep 17 00:00:00 2001 From: Artem Bityutskiy Date: Mon, 28 Sep 2009 11:50:51 +0300 Subject: ubinize/ubiformat: improve random number seeding Add current time to the PID to improve the pseudo-random number generator seeding. Also, use 'rand()' instead of 'random()', because 'srand()' is for 'rand()'. Signed-off-by: Artem Bityutskiy --- ubi-utils/src/common.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'ubi-utils/src/common.c') diff --git a/ubi-utils/src/common.c b/ubi-utils/src/common.c index 3fd470b..da5156d 100644 --- a/ubi-utils/src/common.c +++ b/ubi-utils/src/common.c @@ -23,10 +23,13 @@ * Adrian Hunter */ +#include +#include #include #include #include #include +#include #include "common.h" /** @@ -175,3 +178,32 @@ void ubiutils_print_text(FILE *stream, const char *text, int width) ++p; } } + +/** + * ubiutils_srand - randomly seed the standard pseudo-random generator. + * + * This helper function seeds the standard libc pseudo-random generator with a + * more or less random value to make sure the 'rand()' call does not return the + * same sequence every time UBI utilities run. Returns zero in case of success + * and a %-1 in case of error. + */ +int ubiutils_srand(void) +{ + struct timeval tv; + struct timezone tz; + unsigned int seed; + + /* + * Just assume that a combination of the PID + current time is a + * reasonably random number. + */ + if (gettimeofday(&tv, &tz)) + return -1; + + seed = (unsigned int)tv.tv_sec; + seed += (unsigned int)tv.tv_usec; + seed *= getpid(); + seed %= RAND_MAX; + srand(seed); + return 0; +} -- cgit v1.2.3