Skip to content

Instantly share code, notes, and snippets.

@oza
Created November 20, 2009 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oza/239357 to your computer and use it in GitHub Desktop.
Save oza/239357 to your computer and use it in GitHub Desktop.
/**
* How to compile in linux :
* gcc -lrt posix_timer.c
* to link posix timer functions.
*/
#include <stdio.h>
#include <time.h>
#include <signal.h>
#define SIGNO SIGUSR1
#define THREAD_TIMER
#define USE_ABSTIMER
struct posix_timer {
struct itimerspec ts;
timer_t timer;
};
int timer_flag;
#ifdef THREAD_TIMER
void timer_handler(union sigval v)
{
struct posix_timer* pt;
pt = (struct posix_timer*) v.sival_ptr;
printf("[%s]sigval_int %p\n",__FUNCTION__,pt);
#ifdef USE_ABSTIMER
clock_gettime( CLOCK_REALTIME, &(pt->ts.it_value) );
pt->ts.it_value.tv_sec += 1;
#endif
timer_settime(&pt->timer,timer_flag,&pt->ts,NULL);
}
#else
static void sigtimer_handler(int signo,siginfo_t *si,void *ucontext)
{
struct posix_timer* pt;
pt = (struct posix_timer*) si->si_ptr;
printf("[%s]sigval_int %p\n",__FUNCTION__,pt);
#ifdef USE_ABSTIMER
clock_gettime( CLOCK_REALTIME, &(pt->ts.it_value) );
pt->ts.it_value.tv_sec += 1;
#endif
timer_settime(&pt->timer,timer_flag,&pt->ts,NULL);
}
#endif
main()
{
int ret;
struct sigevent evp;
struct posix_timer pt;
#ifdef THREAD_TIMER
evp.sigev_notify = SIGEV_THREAD;
evp.sigev_notify_function = timer_handler;
evp.sigev_value.sival_ptr = &pt;
evp.sigev_notify_attributes = NULL;
#else
struct sigaction act;
sigset_t set;
act.sa_sigaction = sigtimer_handler;
act.sa_flags |= SA_SIGINFO;
sigemptyset(&set);
sigaddset(&set,SIGNO);
sigprocmask(SIG_UNBLOCK,&set,NULL);
if( sigaction(SIGNO,&act,NULL) < 0 ){
perror("sigaction");
}
evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = SIGNO;
evp.sigev_value.sival_ptr = &pt;
#endif // THREAD_TIMER
#ifdef USE_ABSTIMER
clock_gettime( CLOCK_REALTIME, &(pt.ts.it_value) );
pt.ts.it_value.tv_sec += 1;
clock_gettime( CLOCK_REALTIME, &(pt.ts.it_interval) );
pt.ts.it_value.tv_nsec += 2; // this program doesn't use this.
timer_flag = TIMER_ABSTIME;
#else
pt.ts.it_value.tv_sec = 1;
pt.ts.it_value.tv_nsec = 0;
pt.ts.it_interval.tv_nsec = 2; // this program doesn't use this.
pt.ts.it_interval.tv_nsec = 0;
timer_flag = 0;
#endif // USE_ABSTIMER
/* set timerid and evp */
ret = timer_create(CLOCK_REALTIME,&evp,&pt.timer);
if ( ret < 0 )
perror("timer_create");
ret = timer_settime(pt.timer,timer_flag,&pt.ts,NULL);
if ( ret < 0 )
perror("timer_settime");
while(1){
pause();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment