Linux系统新定时器句柄timerfd的使用

主要数据结构

struct timespec {
  time_t tv_sec;                /* Seconds */
  long   tv_nsec;               /* 纳秒级别 */
};

struct itimerspec {
  struct timespec it_interval;  /* 间隔时间*/
  struct timespec it_value;     /* 初始化时间 */
};
#include 
#include 
#include 
#include 
using namespace std;

int main() {
    struct timespec now ;
    if(clock_gettime(CLOCK_REALTIME, &now) == -1) {
        return -1 ;
    }
    struct itimerspec itime ;
    //设置初始时间
    itime.it_value.tv_sec = now.tv_sec ; //初试时间是当前时间,刚开始将会触发一次可读事件
    itime.it_value.tv_nsec = now.tv_nsec ;  

    //设置间隔时间
    itime.it_interval.tv_sec = 5 ; //seconds
    itime.it_interval.tv_nsec = 0 ; //(ns)//精度太高不需要
    
    int fd = timerfd_create(CLOCK_REALTIME, 0) ;
    if(fd < 0) {
        return -1 ;
    }
    if(timerfd_settime(fd,TFD_TIMER_ABSTIME, &itime, NULL) == -1) {
        return -1 ;
    }
    int sum = 0 ;
    while(1) {
        uint64_t res ;
        int ret = read(fd, &res, sizeof(res)) ;
        if(ret == -1) {
            return -1 ;
        }
        sum += res ;
        cout << sum<<"   " << res << endl ;
    }
    close(fd) ;
    return 0;
}

你可能感兴趣的:(Linux系统,LinuxC编程)