Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save frank-liu/5083159 to your computer and use it in GitHub Desktop.
Save frank-liu/5083159 to your computer and use it in GitHub Desktop.
/*
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment