timer_linux.c (1394B)
1 /* see LICENSE file for copyright and license details */ 2 #include "../timer.h" 3 4 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) 5 #include <errno.h> 6 #include <poll.h> 7 #include <stdint.h> 8 #include <sys/timerfd.h> 9 #include <unistd.h> 10 11 static int timers[TIMER_MAX]; 12 static int ntimers; 13 14 int 15 timer_init(int n) 16 { 17 if (n > TIMER_MAX) { 18 errno = EINVAL; 19 return -1; 20 } 21 for (ntimers = 0; ntimers < n; ntimers++) { 22 timers[ntimers] = timerfd_create(CLOCK_BOOTTIME, TFD_CLOEXEC); 23 if (timers[ntimers] == -1) 24 return -1; 25 } 26 return 0; 27 } 28 29 int 30 timer_set(int i, const struct timespec *ts) 31 { 32 struct itimerspec its = {0}; 33 34 its.it_value = *ts; 35 return timerfd_settime(timers[i], 0, &its, NULL); 36 } 37 38 int 39 timer_left(int i, struct timespec *ts) 40 { 41 struct itimerspec its; 42 43 if (timerfd_gettime(timers[i], &its) < 0) 44 return -1; 45 *ts = its.it_value; 46 return 0; 47 } 48 49 int 50 timer_wait(int fd) 51 { 52 struct pollfd pfd[TIMER_MAX + 1]; 53 uint64_t n; 54 int i, fired = 0; 55 56 pfd[0].fd = fd; 57 pfd[0].events = POLLIN; 58 for (i = 0; i < ntimers; i++) { 59 pfd[i + 1].fd = timers[i]; 60 pfd[i + 1].events = POLLIN; 61 } 62 if (poll(pfd, ntimers + 1, -1) == -1) 63 return -1; 64 if (pfd[0].revents) 65 return 0; 66 for (i = 0; i < ntimers; i++) { 67 if (pfd[i + 1].revents) { 68 fired |= 1 << i; 69 read(timers[i], &n, sizeof(n)); 70 } 71 } 72 return fired; 73 } 74 #endif