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