5.28 Linux新增进程间通信API: timerfd

1、实验代码
信号是中断的,可能导致其他问题,是异步通知;而文件I/O是进程内部阻塞的

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <sys/timerfd.h>

#define handle_error(msg) \
    do{perror(msg);exit(EXIT_FAILURE);}while(0)

void print_time ()
{
    struct timeval tv;
    gettimeofday (&tv, NULL);
    printf ("current time: %ld.%ld\n", tv.tv_sec, tv.tv_usec);
}

int main (int argc, char *argv[])
{
    struct timespec now;
    if (clock_gettime (CLOCK_REALTIME, &now) == -1)
        handle_error ("clock_gettime");

    struct itimerspec new_value;
    new_value.it_value.tv_sec = now.tv_sec + 10; // 10s later,timer will timeout
    new_value.it_value.tv_nsec = now.tv_nsec;
    new_value.it_interval.tv_sec = 3;  //timer intelval
    new_value.it_interval.tv_nsec = 0;

    int fd = timerfd_create (CLOCK_REALTIME, 0);
    if (fd == -1)
        handle_error ("timerfd_creat");
    if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
        handle_error ("timerfd_settime");

    print_time ();
    printf ("timer started\n");

    for (uint64_t tot_exp = 0; tot_exp < 20;) //timer run times: 20
    {
        uint64_t exp;
        ssize_t s = read (fd, &exp, sizeof(uint64_t));
        if (s != sizeof(uint64_t))
            handle_error ("read");
        tot_exp += exp;
        print_time ();
        printf ("read: %llu, total: %llu\n", exp, tot_exp);
    }

    return 0;
}

2、实验结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值