alex

how to implement a timer

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>


timer_t mytimer;

extern "C" void timer_intr(int sig, siginfo_t *extra, void *cruft)
{
        printf("timer_intr called\n");
}

int main()
{
        sigset_t sigset;

        sigfillset(&sigset);
        sigdelset(&sigset, SIGRTMIN);
        sigprocmask(SIG_SETMASK, &sigset, NULL);

        struct sigaction sa;
        sigfillset(&sa.sa_mask);
        sa.sa_flags = SA_SIGINFO;
        sa.sa_sigaction = timer_intr;

        if(sigaction(SIGRTMIN, &sa, NULL) < 0)
        {
                perror("timer thread: sigaction..\n");
                exit(-2);
        }

        struct sigevent timer_event;
        struct itimerspec timer;

        timer.it_interval.tv_sec = 0;
        timer.it_interval.tv_nsec = 999 * 1000 * 1000;
        timer.it_value = timer.it_interval;

        timer_event.sigev_notify = SIGEV_SIGNAL;
        timer_event.sigev_signo = SIGRTMIN;
        timer_event.sigev_value.sival_ptr = (void *)&mytimer;

        if(timer_create(CLOCK_REALTIME, &timer_event, &mytimer) < 0)
        {
                perror("timer_create");
                exit(-1);
        }

        if(timer_settime(mytimer, 0, &timer, NULL) < 0)
        {
                perror("timer_settime");
                exit(-1);
        }

        while(1)
        {
                pause();
        }

        return 0;
}

posted on 2007-08-08 10:46 alex 阅读(319) 评论(0)  编辑 收藏 引用 所属分类: Technique


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理