linux time_t使用

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/wteruiycbqqvwt/article/details/89398903

方式一

#include <stdio.h> 
#include <signal.h> 
#include <time.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
 
void timer_thread(union sigval v) { 
    printf("timer_thread function! %d\n", v.sival_int); 
} 
 
int main() 
{ 
    timer_t timerid; 
    struct sigevent evp; 
    memset(&evp, 0, sizeof(struct sigevent));       //清零初始化 
 
    evp.sigev_value.sival_int = 111;                //是标识定时器的,回调函数可以获得  
    evp.sigev_notify = SIGEV_THREAD;                //线程通知的方式,派驻新线程
    evp.sigev_notify_function = timer_thread;       //线程函数地址
 
    if (timer_create(CLOCK_REALTIME, &evp, &timerid) == -1)  {   
        perror("fail to timer_create"); 
        exit(-1); 
    }   
 
    /*第一次间隔it.it_value这么长,以后每次都是it.it_interval这么长,就是说it.it_value变0的时候会>装载it.it_interval的值 */
    struct itimerspec it; 
    it.it_interval.tv_sec = 1;  // 回调函数执行频率为1s运行1次
    it.it_interval.tv_nsec = 0; 
    it.it_value.tv_sec = 3;     // 倒计时3秒开始调用回调函数
    it.it_value.tv_nsec = 0; 
 
    if (timer_settime(timerid, 0, &it, NULL) == -1)  {   
        perror("fail to timer_settime"); 
        exit(-1); 
    }   
 
    //pause();
    while (1);
 
    return 0; 
} 

方式二

#include <stdio.h> 
#include <time.h> 
#include <stdlib.h> 
#include <signal.h> 
#include <string.h> 
#include <unistd.h> 
#define CLOCKID CLOCK_REALTIME 
 
void sig_handler(int signo) { 
    printf("timer_signal function! %d\n", signo); 
} 
 
int main() 
{ 
    // XXX int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); 
    // signum--指定的信号编号,可以指定SIGKILL和SIGSTOP以外的所有信号编号 
    // act结构体--设置信号编号为signum的处理方式 
    // oldact结构体--保存上次的处理方式 
    timer_t timerid; 
    struct sigevent evp; 
 
    struct sigaction act; 
    memset(&act, 0, sizeof(act)); 
    act.sa_handler = sig_handler; 
    act.sa_flags = 0;  
    sigemptyset(&act.sa_mask); 
    
    if (sigaction(SIGUSR1, &act, NULL) == -1)  { 
        perror("fail to sigaction"); 
        exit(-1); 
    } 
 
    memset(&evp, 0, sizeof(struct sigevent)); 
    evp.sigev_signo = SIGUSR1; 
    evp.sigev_notify = SIGEV_SIGNAL; 
    evp.sigev_value.sival_ptr = &timerid; 
    if (timer_create(CLOCK_REALTIME, &evp, &timerid) == -1)  { 
        perror("fail to timer_create"); 
        exit(-1); 
    } 
 
    struct itimerspec it; 
    it.it_interval.tv_sec = 2; 
    it.it_interval.tv_nsec = 0; 
    it.it_value.tv_sec = 1; 
    it.it_value.tv_nsec = 0; 
    if (timer_settime(timerid, 0, &it, 0) == -1) { 
        perror("fail to timer_settime"); 
        exit(-1); 
    } 
 
    pause();
    return 0; 
} 

猜你喜欢

转载自blog.csdn.net/wteruiycbqqvwt/article/details/89398903
今日推荐