From 835a144d6e2d3211c2131cc034ede88a86d86b3b Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Sun, 21 Feb 2016 15:56:07 -0800 Subject: [PATCH] Genericize the rand code. --- adsbus/adsbus.c | 4 ++-- adsbus/common.c | 19 ++++++++++++------- adsbus/common.h | 7 +++++++ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/adsbus/adsbus.c b/adsbus/adsbus.c index a6634c9..8824206 100644 --- a/adsbus/adsbus.c +++ b/adsbus/adsbus.c @@ -102,7 +102,7 @@ int main(int argc, char *argv[]) { hex_init(); peer_init(); - retry_init(); + rand_init(); wakeup_init(); send_init(); @@ -117,7 +117,7 @@ int main(int argc, char *argv[]) { peer_loop(); - retry_cleanup(); + rand_cleanup(); wakeup_cleanup(); send_cleanup(); diff --git a/adsbus/common.c b/adsbus/common.c index 0f384fe..f7b01fd 100644 --- a/adsbus/common.c +++ b/adsbus/common.c @@ -218,17 +218,22 @@ void uuid_gen(char *out) { } -static int retry_rand_fd; +static int rand_fd; -void retry_init() { - retry_rand_fd = open("/dev/urandom", O_RDONLY); - assert(retry_rand_fd >= 0); +void rand_init() { + rand_fd = open("/dev/urandom", O_RDONLY); + assert(rand_fd >= 0); } -void retry_cleanup() { - assert(!close(retry_rand_fd)); +void rand_cleanup() { + assert(!close(rand_fd)); } +void rand_fill(void *value, size_t size) { + assert(read(rand_fd, value, size) == size); +} + + #define RETRY_MIN_MS 2000 #define RETRY_MAX_MS 64000 #define RETRY_MULT 2 @@ -240,7 +245,7 @@ uint32_t retry_get_delay_ms(uint32_t prev_delay) { uint32_t max_jitter = delay / RETRY_MAX_JITTER_DIV; uint32_t jitter; - assert(read(retry_rand_fd, &jitter, sizeof(jitter)) == sizeof(jitter)); + rand_fill(&jitter, sizeof(jitter)); delay += jitter % max_jitter; delay = delay > RETRY_MAX_MS ? RETRY_MAX_MS : delay; diff --git a/adsbus/common.h b/adsbus/common.h index 7427d82..285db73 100644 --- a/adsbus/common.h +++ b/adsbus/common.h @@ -93,6 +93,13 @@ void hex_from_int(char *, uint64_t, size_t); void uuid_gen(char *); +///////// rand + +void rand_init(); +void rand_cleanup(); +void rand_fill(void *, size_t); + + ///////// retry timing void retry_init();