diff --git a/lib/mosquitto.c b/lib/mosquitto.c index a83d43a7..7043604b 100644 --- a/lib/mosquitto.c +++ b/lib/mosquitto.c @@ -38,6 +38,7 @@ Contributors: #include "mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" +#include "time_mosq.h" #include "will_mosq.h" static unsigned int init_refcount = 0; @@ -57,15 +58,15 @@ int mosquitto_lib_init(void) int rc; if (init_refcount == 0) { + mosquitto_time_init(); #ifdef WIN32 srand((unsigned int)GetTickCount64()); #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; #ifdef CLOCK_BOOTTIME - clock_gettime(CLOCK_BOOTTIME, &tp); -#else - clock_gettime(CLOCK_MONOTONIC, &tp); + if (clock_gettime(CLOCK_BOOTTIME, &tp) != 0) #endif + clock_gettime(CLOCK_MONOTONIC, &tp); srand((unsigned int)tp.tv_nsec); #elif defined(__APPLE__) uint64_t ticks; diff --git a/lib/time_mosq.c b/lib/time_mosq.c index 110322a4..2dd28d4a 100644 --- a/lib/time_mosq.c +++ b/lib/time_mosq.c @@ -36,6 +36,27 @@ Contributors: #include "mosquitto.h" #include "time_mosq.h" +#if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) +static clockid_t time_clock; +#endif + +void mosquitto_time_init(void) +{ +#if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) + struct timespec tp; + +#ifdef CLOCK_BOOTTIME + if (clock_gettime(CLOCK_BOOTTIME, &tp) == 0) { + time_clock = CLOCK_BOOTTIME; + } else { + time_clock = CLOCK_MONOTONIC; + } +#else + time_clock = CLOCK_MONOTONIC; +#endif +#endif +} + time_t mosquitto_time(void) { #ifdef WIN32 @@ -43,12 +64,10 @@ time_t mosquitto_time(void) #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; -#ifdef CLOCK_BOOTTIME - clock_gettime(CLOCK_BOOTTIME, &tp); -#else - clock_gettime(CLOCK_MONOTONIC, &tp); -#endif - return tp.tv_sec; + if (clock_gettime(time_clock, &tp) == 0) + return tp.tv_sec; + + return (time_t) -1; #elif defined(__APPLE__) static mach_timebase_info_data_t tb; uint64_t ticks; diff --git a/lib/time_mosq.h b/lib/time_mosq.h index 93d4fc24..ba139c13 100644 --- a/lib/time_mosq.h +++ b/lib/time_mosq.h @@ -19,6 +19,7 @@ Contributors: #ifndef TIME_MOSQ_H #define TIME_MOSQ_H +void mosquitto_time_init(void); time_t mosquitto_time(void); #endif