头文件与函数
#include <sys/select.h>
int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
void FD_CLR(int fd, fd_set *set); //将set中第fd位清除
int FD_ISSET(int fd, fd_set *set);//判断set中第fd位是否位1,是返回1否返回1
void FD_SET(int fd, fd_set *set); //将set中第fd位设置为1
void FD_ZERO(fd_set *set);//将fd中所有位清除
fd_set可以看成一个数组,里面存着文件描述符。
readfds可读文件描述符集合
witefds可写文件描述符集合
execeptfds可执行文件描述符集合
n:所有集合中最大的文件描述符加1
struct timeval{ long tv_sec; /*秒 */ long tv_usec; /*微秒 */ } timeout表示select函数等待时间。 将select函数第一个参数设置为0,第二三四参数设置为NULL,最后一个参数设置为时间,可以当定时器用。 struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 1000; select(0, NULL, NULL, NULL, &tv); 实例,每0.5s执行一次函数
#include <sys/time.h> #include <sys/select.h> #include <stdio.h> //mseconds: micro seconds 1s = 1000000us void setTimer(int seconds, int useconds) { struct timeval temp; temp.tv_sec = seconds; temp.tv_usec = useconds; select(0, NULL, NULL, NULL, &temp); printf("timer interval: %ds %dus\n", seconds, useconds); return; } int main() { int i; for (i=0; i<10; i++) { setTimer(0, 500000); } return 0; }使用poll()来作为毫秒精度定时器
原理与select一样,都是监视空文件描述符并等待超时。
#include <sys/time.h> #include <stdio.h> #include <poll.h> //mseconds: 定时器毫秒 void setPollTimer(int mseconds) { struct pollfd fds[1]; fds[0].fd = 0; fds[0].events = POLLIN; poll(fds, 1, mseconds); printf("this is poll timer\n"); } int main() { int i; for (i=0; i<10; i++) { setPollTimer(2000); } return 0; }