From: Lennart Poettering Date: Wed, 16 Jun 2010 03:05:36 +0000 (+0200) Subject: util: introduce random_ull() X-Git-Tag: v1~192 X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=commitdiff_plain;h=d3782d60cd47f57f48a9229bdd3badbd2f4bae44 util: introduce random_ull() --- diff --git a/src/util.c b/src/util.c index 2bc90da3d..71409034a 100644 --- a/src/util.c +++ b/src/util.c @@ -2141,6 +2141,26 @@ int dir_is_empty(const char *path) { return r; } +unsigned long long random_ull(void) { + int fd; + uint64_t ull; + ssize_t r; + + if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0) + goto fallback; + + r = loop_read(fd, &ull, sizeof(ull)); + close_nointr_nofail(fd); + + if (r != sizeof(ull)) + goto fallback; + + return ull; + +fallback: + return random() * RAND_MAX + random(); +} + static const char *const ioprio_class_table[] = { [IOPRIO_CLASS_NONE] = "none", [IOPRIO_CLASS_RT] = "realtime", diff --git a/src/util.h b/src/util.h index cacc3969b..0b397ac0d 100644 --- a/src/util.h +++ b/src/util.h @@ -196,6 +196,8 @@ int make_stdio(int fd); bool is_clean_exit(int code, int status); +unsigned long long random_ull(void); + #define DEFINE_STRING_TABLE_LOOKUP(name,type) \ const char *name##_to_string(type i) { \ if (i < 0 || i >= (type) ELEMENTSOF(name##_table)) \