当前位置:网站首页>系统编程之高级文件IO(十三)——IO多路复用-select
系统编程之高级文件IO(十三)——IO多路复用-select
2022-04-23 11:15:00 【光追雨】
一、IO多路复用
IO多路复用就是IO被阻塞状态下,做其他事情
二、select
实现功能:监听;可以监听很多的文件描述符
原型:int select(int maxfd, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout)
fd_set:文件描述符集合,一个容器,可以保存很数据(文件描述符)的数组
maxfd:文件描述符的范围,比待检的最大文件描述符大1
readfds:被读监控的文件描述符集
writefds:被写监控的文件描述符集
exceptfds:被异常监控的文件描述符集
timeval:系统定义时间
返回值,成功返回变化的个数、失败返回-1
一般用来监听读
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char const *argv[])
{
struct timeval time;
fd_set r_set;
fd_set all_set;
time.tv_sec = 3;
time.tv_usec = 0;
int fd;
if((fd = open("/dev/input/mouse0", O_RDWR | O_CREAT, 0655)) < 0)
{
perror("open file error!");
exit(1);
}
FD_SET(fd, &r_set);
FD_SET(0, &r_set);
all_set = r_set; //暂存如all_set
while (1)
{
r_set = all_set; //每次都进行置位,不然之后每次只会监听变化的那个
int ret = select(fd + 1, &r_set, NULL, NULL, NULL );
if (FD_ISSET(fd, &r_set) > 0)
{
int cor;
read(fd, &cor, sizeof(cor));
printf("cor = %d\n", cor);
}
if (FD_ISSET(0, &r_set) > 0)
{
char buffer[1024];
read(0, buffer, sizeof(buffer));
printf("buffer = %s\n", buffer);
}
}
return 0;
}
附、一些补充
fd_set……
timeval
int select(int maxfd, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout)
(百度解释)
参数一:最大的文件描述符加1。
参数二:用于检查可读性,
参数三:用于检查可写性,
参数四:用于检查带外数据,
参数五:一个指向timeval结构的指针,用于决定select等待I/o的最长时间,等完直接回来。如果为空将一直等待(NULL)。
timeval结构的定义:
struct timeval
{
long tv_sec; // seconds秒
long tv_usec; // microseconds毫秒
}
版权声明
本文为[光追雨]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_52592798/article/details/124348977
边栏推荐
- Constraintlayout layout
- 学习 Go 语言 0x05:《Go 语言之旅》中映射(map)的练习题代码
- Learn go language 0x06: Fibonacci closure exercise code in go language journey
- GO接口使用
- MIT:用无监督为世界上每个像素都打上标签!人类:再也不用为1小时视频花800个小时了
- Mba-day6 logic - hypothetical reasoning exercises
- Software testers, how to mention bugs?
- Learn go language 0x07: stringer exercise code in go language journey
- Visualization Road (10) detailed explanation of segmentation canvas function
- Learning go language 0x02: understanding slice
猜你喜欢
随机推荐
《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐
Mba-day6 logic - hypothetical reasoning exercises
Common parameters of ffmpeg command line
An interesting interview question
Excel·VBA自定义函数获取单元格多数值
MySQL interview questions explain how to set hash index
MBA-day5數學-應用題-工程問題
MIT:用无监督为世界上每个像素都打上标签!人类:再也不用为1小时视频花800个小时了
学习 Go 语言 0x05:《Go 语言之旅》中映射(map)的练习题代码
初探 Lambda Powertools TypeScript
How to quickly query 10 million pieces of data in MySQL
MySQL数据库10秒内插入百万条数据的实现
Learning go language 0x02: understanding slice
oh-my-lotto
小程序 支付
Cumcm 2021 - B: préparation d'oléfines C4 par couplage éthanol (2)
Visualized common drawing (II) line chart
R-drop: a more powerful dropout regularization method
Promise details
Use of SVN: