]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
lib/randutils: add xsrand() and rand_get_number()
authorKarel Zak <kzak@redhat.com>
Tue, 6 Sep 2016 08:19:52 +0000 (10:19 +0200)
committerKarel Zak <kzak@redhat.com>
Tue, 6 Sep 2016 08:19:52 +0000 (10:19 +0200)
Signed-off-by: Karel Zak <kzak@redhat.com>
include/randutils.h
lib/randutils.c

index 17e2a02fac07701f2f01c94216a3ddc91c3766ba..7094a4c74078fe8761286b860b3cb1cc463508dc 100644 (file)
@@ -6,6 +6,11 @@
 #define rand()         random()
 #endif
 
+/* rand() based */
+extern void xsrand(void);
+extern int rand_get_number(int low_n, int high_n);
+
+/* /dev/urandom based with fallback to rand() */
 extern int random_get_fd(void);
 extern void random_get_bytes(void *buf, size_t nbytes);
 extern const char *random_tell_source(void);
index 684ac0ac160af22e0442368f21c6881884a9ae0d..2e124bcb66ab038df17f4f6b7c7f178e21af5368 100644 (file)
 THREAD_LOCAL unsigned short ul_jrand_seed[3];
 #endif
 
+void xsrand(void)
+{
+       struct timeval tv;
+
+       gettimeofday(&tv, 0);
+       srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
+}
+
+int rand_get_number(int low_n, int high_n)
+{
+       return rand() % (high_n - low_n + 1) + low_n;
+}
+
 int random_get_fd(void)
 {
        int i, fd;
-       struct timeval  tv;
+       struct timeval tv;
 
-       gettimeofday(&tv, 0);
        fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
        if (fd == -1)
                fd = open("/dev/random", O_RDONLY | O_NONBLOCK | O_CLOEXEC);
@@ -44,7 +56,7 @@ int random_get_fd(void)
                if (i >= 0)
                        fcntl(fd, F_SETFD, i | FD_CLOEXEC);
        }
-       srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
+       xsrand();
 
 #ifdef DO_JRAND_MIX
        ul_jrand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);