I have a program which creates a timer using timerfd_create (the timer when it expires, sets a file descriptor).
Problem is, i am using epoll_wait to wait for the file descriptor, then checking for the expiration using fd=revent.data.fd and fd=timer_fd (see program below).
But if i do this, epoll_wait blocks my program till timer expires, and i don’t want this to happen..i want the program to run, and periodically i will check for timer expire. Is there any alternative approach to that?
Please see the program below.
enter code here
#include <sys/timerfd.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <time.h>
int main()
{
struct itimerspec its;
struct epoll_event event, revent;
int timer_fd, efd, fd1, fd2;
/* Setting timer interval */
its.it_interval.tv_sec=1;
its.it_interval.tv_nsec=0;
/* Setting timer expiration */
its.it_value.tv_sec=5;
its.it_value.tv_nsec=0;
efd=epoll_create(2);
timer_fd=timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
event.data.fd=timer_fd;
event.events=EPOLLIN|EPOLLPRI;
epoll_ctl(efd, EPOLL_CTL_ADD, timer_fd, &event);
if(timer_fd==-1)
{
fprintf(stderr,"timerfd_settime error:");
exit;
}
if(timerfd_settime(timer_fd, 0, &its, NULL)==-1)
{
fprintf(stderr,"timerfd_settime error:");
exit;
}
printf("Starting the timer...");
fd1=epoll_wait(efd, &revent, 1, -1);
if(fd1<0) {
fprintf(stderr, "epoll_wait error\n");
exit;
}
else {
fprintf(stdout, "number of fds: %d",fd1);
}
fd2=revent.data.fd;
if(fd2==timer_fd) {
printf("Timer expired\n");
// IMPORTANT: This i want to check periodically without epoll_wait which blocks the program, What is the alternative?
}
}
Instead of polling with epoll, since you’re only waiting on one timer you can just check if it’s expired by
reading it. The number of times it has expired will then be stored in the buffer that you’rereading into, or if it hasn’t expired, thereadwill fail with the error EAGAIN.Note that you’ll need to initialize
timer_fdwith the flagTFD_NONBLOCK, or else thereadwill block if it hasn’t expired yet rather than fail, but you already do that.