Skip to content

Instantly share code, notes, and snippets.

@oza
Created December 24, 2009 06:18
Show Gist options
  • Select an option

  • Save oza/263051 to your computer and use it in GitHub Desktop.

Select an option

Save oza/263051 to your computer and use it in GitHub Desktop.
all:
gcc timerfd.c -o timerfd
test:
./timerfd
clean:
rm -rf timerfd
/* timerfd.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <time.h>
#include <signal.h>
#include <stdint.h>
struct posix_timer {
int tfd;
struct itimerspec ts;
timer_t timer;
};
int efd;
struct epoll_event ev;
void do_handle(struct posix_timer *pt)
{
int tfd = pt->tfd;
printf("handled! pt %p\n",pt);
pt->ts.it_value.tv_sec = 1;
pt->ts.it_value.tv_nsec = 0;
pt->ts.it_interval.tv_sec = 0;
pt->ts.it_interval.tv_nsec = 0;
timerfd_settime( tfd, 0, &pt->ts, NULL );
}
void start_epoll( int fd, void* data )
{
int ret;
int buf;
struct epoll_event ev,events;
struct posix_timer* pt;
/* init */
efd = epoll_create(1);
ev.events = EPOLLIN;
ev.data.ptr = data;
if( epoll_ctl(efd,EPOLL_CTL_ADD,fd,&ev) == -1 ){
perror("epoll_ctl");
exit(1);
}
while(1){
printf("start to epoll wait...\n");
ret = epoll_wait(efd, &events, 1, -1);
if( ret < 0 ){
perror("epoll_wait");
exit(1);
}
printf("read...\n");
pt = events.data.ptr;
/* events is overwritten by epoll_wait, and have ev.data.fd */
read( pt->tfd, &buf, sizeof(uint64_t) );
printf("[%s] ret %d buf %d \n",__FUNCTION__,ret,buf);
do_handle( pt );
}
exit(1);
}
main()
{
int cnt = 0;
struct posix_timer pt;
pt.tfd = timerfd_create( CLOCK_REALTIME, 0 );
if ( pt.tfd < 0 ){
perror("timerfd_create");
exit(1);
}
pt.ts.it_value.tv_sec = 10;
pt.ts.it_value.tv_nsec = 0;
pt.ts.it_interval.tv_sec = 0;
pt.ts.it_interval.tv_nsec = 0;
// run timer with rel-timer mode.
if ( timerfd_settime( pt.tfd, 0, &pt.ts, NULL ) ){
perror("timerfd_settime");
exit(1);
}
if ( fork() == 0 ){
start_epoll( pt.tfd, &pt );
}
while(1){
pause();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment