select函数用法
来源:互联网 发布:哪里购买域名比较好 编辑:程序博客网 时间:2024/05/17 09:15
select函数可以实现I/O多路复用,简单地说就是一个线程最多可以监听1024个I/O,一旦某一个I/O就绪,就可以进行相应的读写操作。
函数原型:int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
参数说明:
nfds:最大文件描述符+1,因为描述符编号从0开始,所以要在最大描述符编号上加1。实际上就是要检查的描述符。
readfds、writefds、exceptfds:这三个参数是指向fd_set结构体的指针,其中readfds表示文件描述符集合中是否有可读的文件描述符,如果有,select()就会返回一个大于0的数,表示有文件可读,如果没有,再根据timout的值判断是否超时,如果超时select()返回0,若发生错误,select()返回负值,也可以传入NULL,表示不关心任何文件描述符的可读情况。类似的,writefds记录文件描述符中的可写情况,exceptfds记录文件描述符中的错误异常情况。
timeout:设置超时时间
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
timeout==NULL,表示永远等待。
timeout->tv_sec==0 && timeout->tv_usec==0,表示不等待。
timeout->tv_sec!=0 && timeout->tv_usec!=0,表示等待指定的毫秒数和微妙数。
void FD_CLR(int fd, fd_set *set); //清除fd_set 结构体中的fd成员
int FD_ISSET(int fd, fd_set *set);//检测fd_set 结构体中fd成员是否为真
void FD_SET(int fd, fd_set *set);//设置fd_set 结构体中fd成员
void FD_ZERO(fd_set *set);//清空fd_set 结构体
demo:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <errno.h> #include <sys/select.h>#include <sys/types.h>#include <sys/time.h>#include <unistd.h>#include <fcntl.h> #include <errno.h> #include <time.h> #include <linux/input.h>#define DEVICE "/dev/input/event0" int main(int argc, char **argv) { int fd = 0; fd_set readfd; struct timeval tv; int ret; struct input_event t; FD_ZERO(&readfd); fd = open(DEVICE, O_RDONLY); FD_SET(fd, &readfd); tv.tv_sec = 5; tv.tv_usec = 0; printf("open %s fd = %d\n",DEVICE ,fd); ret = select(fd+1, &readfd, NULL, NULL, NULL); if (ret < 0) { perror("nselect"); } else if (ret == 0) { printf("timeout\n"); } else { printf("ret = %d\n",ret); } if (FD_ISSET(fd, &readfd)) { if(read(fd, &t, sizeof(t)) == sizeof(t)) { printf("type = %d, code = %d, value = %s\n",t.type, t.code, (t.value) ? "Pressed" : "Released"); } } close(fd); return 0;}
- linux select 函数用法!
- select 函数用法
- linux select 函数用法!
- linux select函数用法
- linux select 函数用法!
- linux select函数用法
- select 函数用法--续
- select函数的用法
- select函数用法
- select()函数用法
- select函数用法
- linux select函数用法
- linux select函数用法
- linux select函数用法
- linux select函数用法
- linux select函数用法
- linux select函数用法
- select函数用法
- MyBatis学习 之 二、SQL语句映射文件(1)resultMap
- Android与服务器通信的方法之一(TCP)效率高安全性完善
- Jquery事件的显示与隐藏
- django 登录和session过期跳转
- Spring AOP+Log4j记录项目日志
- select函数用法
- Introduction of CFD(计算流体力学概述)
- windows的SOCKET编程
- 【IMWeb训练营作业】 vue练习-组件select
- javascript面向对象的混入
- 4位流水线乘法器
- JSP内置对象
- 手机网站开发:滑动翻屏效果 jquery触摸屏滑动效果
- Java知识点集锦