make timed kgio_wait_* implementation safer
[kgio.git] / ext / kgio / broken_system_compat.h
blobe67a56c2157da3a0f3b0cb3a22ee42e6b5517802
1 /*
2 * this header includes functions to support broken systems
3 * without clock_gettime() or CLOCK_MONOTONIC
4 */
6 #ifndef HAVE_TYPE_CLOCKID_T
7 typedef int clockid_t;
8 #endif
10 #ifndef HAVE_CLOCK_GETTIME
11 # ifndef CLOCK_REALTIME
12 # define CLOCK_REALTIME 0 /* whatever */
13 # endif
14 static int fake_clock_gettime(clockid_t clk_id, struct timespec *res)
16 struct timeval tv;
17 int r = gettimeofday(&tv, NULL);
19 assert(0 == r && "gettimeofday() broke!?");
20 res->tv_sec = tv.tv_sec;
21 res->tv_nsec = tv.tv_usec * 1000;
23 return r;
25 # define clock_gettime fake_clock_gettime
26 #endif /* broken systems w/o clock_gettime() */
29 * UGH
30 * CLOCK_MONOTONIC is not guaranteed to be a macro, either
32 #ifndef CLOCK_MONOTONIC
33 # if (!defined(_POSIX_MONOTONIC_CLOCK) || !defined(HAVE_CLOCK_MONOTONIC))
34 # define CLOCK_MONOTONIC CLOCK_REALTIME
35 # endif
36 #endif
39 * Availability of a monotonic clock needs to be detected at runtime
40 * since we could've been built on a different system than we're run
41 * under.
43 static clockid_t hopefully_CLOCK_MONOTONIC;
45 static int check_clock(void)
47 struct timespec now;
49 hopefully_CLOCK_MONOTONIC = CLOCK_MONOTONIC;
51 /* we can't check this reliably at compile time */
52 if (clock_gettime(CLOCK_MONOTONIC, &now) == 0)
53 return 1;
55 if (clock_gettime(CLOCK_REALTIME, &now) == 0) {
56 hopefully_CLOCK_MONOTONIC = CLOCK_REALTIME;
57 rb_warn("CLOCK_MONOTONIC not available, "
58 "falling back to CLOCK_REALTIME");
59 return 2;
61 return -1;