Created
October 25, 2016 23:11
-
-
Save troglobit/72b5e451812e92ac01b68e43097605d3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* https://gist.github.com/gdamjan/9560411 */ | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/time.h> | |
#include <sys/timerfd.h> | |
#include <time.h> | |
#include <unistd.h> | |
#define handle_error(msg) \ | |
do { perror(msg); return 1; } while (0) | |
/* Missing defines in GLIBC <= 2.24 */ | |
#ifndef TFD_TIMER_CANCEL_ON_SET | |
#define TFD_TIMER_CANCEL_ON_SET (1 << 1) | |
#endif | |
#ifndef TFD_SETTIME_FLAGS | |
#define TFD_SETTIME_FLAGS (TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET) | |
#endif | |
static void msec2tspec(int msec, struct timespec *ts) | |
{ | |
if (msec) { | |
ts->tv_sec = msec / 1000; | |
ts->tv_nsec = (msec % 1000) * 1000000; | |
} else { | |
ts->tv_sec = 0; | |
ts->tv_nsec = 0; | |
} | |
} | |
/* No cancel on reltime timers, only abstime, Linux <= 4.8 */ | |
int main(int argc, char *argv[]) | |
{ | |
int fd; | |
ssize_t s; | |
uint64_t exp; | |
struct timeval tv; | |
struct itimerspec time; | |
fd = timerfd_create(CLOCK_REALTIME, 0); | |
if (fd == -1) | |
handle_error("timerfd_create"); | |
// msec2tspec(5000, &time.it_value); | |
gettimeofday(&tv, NULL); | |
time.it_value.tv_sec = tv.tv_sec + 3600; | |
time.it_value.tv_nsec = 0; | |
msec2tspec(0, &time.it_interval); | |
if (timerfd_settime(fd, TFD_SETTIME_FLAGS, &time, NULL) == -1) | |
handle_error("timerfd_settime"); | |
s = read(fd, &exp, sizeof(uint64_t)); | |
if (s != sizeof(uint64_t)) | |
handle_error("read"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment