Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Linux file descriptor timers example
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <fcntl.h>
#define TIMEOUT 3
#define POLL_PERIOD 1
int main(int argc, char *argv[])
{
int ret;
int fd = -1;
struct itimerspec timeout;
unsigned long long missed;
/* create new timer */
fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (fd <= 0) {
printf("Failed to create timer\n");
return 1;
}
/* set to non-blocking */
ret = fcntl(fd, F_SETFL, O_NONBLOCK);
if (ret) {
printf("Failed to set to non blocking mode\n");
return 1;
}
/* set timeout */
timeout.it_value.tv_sec = TIMEOUT;
timeout.it_value.tv_nsec = 0;
timeout.it_interval.tv_sec = TIMEOUT; /* recurring */
timeout.it_interval.tv_nsec = 0;
ret = timerfd_settime(fd, 0, &timeout, NULL);
if (ret) {
printf("Failed to set timer duration\n");
return 1;
}
while (1) {
printf("Polling\n");
while (read(fd, &missed, sizeof(missed)) < 0) {
printf("No timer expiry\n");
sleep(POLL_PERIOD);
}
printf("Number of expiries missed: %lld\n", missed);
}
return 0;
}
@rizsi

This comment has been minimized.

Copy link

commented Dec 5, 2018

The accuracy of this solution is defined by the POLL_PERIOD. Using blocking read, epoll or select on the timer file descriptor the best accuracy available on the platform could be achieved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.