select 实现定时 + 轮询

select 定时器 + 轮询(单线程)

上周写了 怎么样获取系统时间

这周写一个 定时 + 轮询 的.

在单线程上实现这个感觉没有什么用,有点多此一举… 但是这个时间的逻辑处理还是可以的…

一、select函数

#include <stdio.h>
#include <time.h>
#include <sys/time.h>


int main(int argc, char const *argv[]){
    int ret = 0;
    fd_set rfds = {0};
    struct timeval tv = {0};


    FD_ZERO(&rfds);
    FD_SET(0, &rfds);

    tv.tv_sec = 1;
    tv.tv_usec = 0;

    ret = select(1, &rfds, NULL, NULL, &tv);

    if(ret == -1){
        perror("select error");
    } else if(ret){
        printf("receive data from to STDIN\n\n");
    }else {
        printf("timeout\n\n");
    }

    return 0;
}

运行结果:

baoshaohua:定时器 bao$ ./select_learning 
timeout

baoshaohua:定时器 bao$ ./select_learning 
d
receive data from to STDIN

baoshaohua:定时器 bao$ d
bash: d: command not found

在 select函数监听标准输入0(键盘), 5s内如果有输入就返回值大于0;
如果没有输入就返回0,表示超时了.

前几天发现, 在使用 man select 的时候, 在mac上的结果没有在Linux系统的结果详细…后面会列举几点.

试了一下其他函数, 也是这样.

所以page还是得在linux上查.

二、应用实例

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <errno.h>


typedef void (* timer_func)(char *param);

//保存定时的时间
int running = 0;
struct timeval duration = {
   0};
struct timeval deadtime = {
   0};
timer_func test_func = NULL;
char *test_func_param = NULL;

int i = 0;

//每次轮询都会计算轮询的时间
void recalculate_time(struct timeval *tv)
{
   
    struct timeval now2;
    struct timeval deadtime2;

    gettimeofday(&now2, NULL);
    memcpy
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值