summaryrefslogtreecommitdiff
path: root/tests/ubi-tests/common.c
diff options
context:
space:
mode:
Diffstat (limited to 'tests/ubi-tests/common.c')
-rw-r--r--tests/ubi-tests/common.c31
1 files changed, 31 insertions, 0 deletions
diff --git a/tests/ubi-tests/common.c b/tests/ubi-tests/common.c
index b605dd9..05cbecc 100644
--- a/tests/ubi-tests/common.c
+++ b/tests/ubi-tests/common.c
@@ -26,8 +26,10 @@
#include <errno.h>
#include <string.h>
#include <unistd.h>
+#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/time.h>
#include <fcntl.h>
#include "libubi.h"
#include "common.h"
@@ -332,3 +334,32 @@ close:
close(fd);
return -1;
}
+
+/**
+ * seed_random_generator - 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 the random seed in case
+ * of success and a %-1 in case of error.
+ */
+int seed_random_generator(void)
+{
+ struct timeval tv;
+ struct timezone tz;
+ 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 %= INT_MAX;
+ srand(seed);
+ return seed;
+}