linux c编程之定时器使用

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

static timer_t timer_id ;//gcc pthread_timer.c -o pthread_timer  -lrt

static void timer_handle()
{
    printf("%s[%d] enter \n",__func__,__LINE__);
}

static void init_timer(int time)
{
    struct sigaction sig_act;
    struct sigevent sig_event;
    struct itimerspec timer_setting;
    
    sigemptyset(&sig_act.sa_mask);
    sig_act.sa_flags = 0;
    sig_act.sa_handler = timer_handle;
    if (sigaction(SIGRTMAX - 1, &sig_act, NULL) < 0) 
    {
        return;
    }

    // set signal event for the timer timeout.
    sig_event.sigev_notify = SIGEV_SIGNAL;
    sig_event.sigev_signo = SIGRTMAX - 1;
    if (timer_create(CLOCK_REALTIME, &sig_event, &timer_id) < 0)
    {
        return;
    }

    timer_setting.it_value.tv_sec = 0;
    timer_setting.it_value.tv_nsec = time * 1000000;
    timer_setting.it_interval.tv_sec = 0;
    timer_setting.it_interval.tv_nsec = time * 1000000;
    if (timer_settime(timer_id, 0, &timer_setting, NULL) < 0)
    {
        return;
    }
}

int main()
{
    init_timer(20); // 100ms

    while( 'q' != getchar() )
	{
		usleep(100000);
	}
	
	timer_delete(timer_id);
	printf("%s[%d] timer_delete(timer_t timerid)\n",__func__,__LINE__);

    return 0;
}

gcc pthread_timer.c -o pthread_timer  -lrt
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 
timer_handle[15] enter 

你可能感兴趣的:(#,linux,c语言,运维)