diff options
author | Artem Bityutskiy <Artem.Bityutskiy@nokia.com> | 2009-09-28 11:50:51 +0300 |
---|---|---|
committer | Artem Bityutskiy <Artem.Bityutskiy@nokia.com> | 2009-09-28 11:50:51 +0300 |
commit | 75d97ca45b74eccc01b18f44040f946d9d5df9f5 (patch) | |
tree | 09f65340037347155934eda7ac2123cc0614915a /ubi-utils/src/common.c | |
parent | 0e63a4c4f1ebc31f545835bd018174414928fc6f (diff) |
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 <Artem.Bityutskiy@nokia.com>
Diffstat (limited to 'ubi-utils/src/common.c')
-rw-r--r-- | ubi-utils/src/common.c | 32 |
1 files changed, 32 insertions, 0 deletions
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 <sys/time.h> +#include <sys/types.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> +#include <unistd.h> #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; +} |