select 定时器 + 轮询(单线程)
上周写了 怎么样获取系统时间
这周写一个 定时 + 轮询 的.
在单线程上实现这个感觉没有什么用,有点多此一举… 但是这个时间的逻辑处理还是可以的…
一、select函数
#include #include #include 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
#include
#include
#include
#include