当前位置:网站首页>为什么poll/select在open时要使用非阻塞NONBLOCK
为什么poll/select在open时要使用非阻塞NONBLOCK
2022-06-23 10:20:00 【stone_322】
1.背景
在学习获取设备信息的四种方式(查询,休眠-唤醒,poll,select)时,发现在使用poll和select时,需要在open时使用1O_NONBLOCK1参数。由于我刚开始没注意这个问题,导致实验现象不正常,这里记录一下。
2.不使用O_NONBLOCK
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
int main(int argc, char **argv)
{
int fd;
int ret;
struct input_event event;
struct pollfd fds[1];
nfds_t nfds = 1;
fd = open(argv[1], O_RDWR); /*| O_NONBLOCK*/
if (fd < 0)
{
return -1;
}
fds[0].fd = fd;
fds[0].events = POLLIN;
while (1)
{
fds[0].revents = 0;
ret = poll(fds, nfds, 3000);
if (ret > 0)
{
if (fds[0].revents == POLLIN)
{
while (read(fd, &event, sizeof(event)) == sizeof(event))
{
printf("get event: type = 0x%x, code = 0x%x, value = 0x%x\n", event.type, event.code, event.value);
}
}
else
{
printf("read error.\n");
}
}
else if(ret == 0)
{
printf("time out\n");
}
else
{
printf("poll err.\n");
}
}
return 0;
}
运行程序,结果如下图所示。可以发现,当我没有按触摸屏的时候,打印time out,这是正常的。当我按一下触摸屏以后,系统打印触摸屏数据,而打印结束后,系统并没有输出time out,如果这时候再按触摸屏,会再次打印触摸屏数据。
3.使用O_NONBLOCK
把上面程序里面的open函数中加入O_NONBLOCK参数,再次编译运行程序,结果如下图。
可以看到,这里的输出是正常的,有数据时上报数据,没数据时打印time out。
4.为什么
在不写O_NONBLOCK时,默认为阻塞方式,所以当按一下触摸屏,系统打印一次数据后,程序会再次执行while (read(fd, &event, sizeof(event)) == sizeof(event))这一句,而此时已经没有内容可读,所以就会卡在这一句。当再次按下触摸屏时,再次打印数据,而再也不会打印time out。
边栏推荐
猜你喜欢

Picture storage -- Reference

RT thread add MSH command
![[software and system security] heap overflow](/img/ca/1b98bcdf006f90cabf3e90e416f7f2.png)
[software and system security] heap overflow

Analysis of LinkedList source code

Shengshihaotong enables high-quality development with industrial Digitalization

Unity技术手册 - 生命周期LifetimebyEmitterSpeed-周期内颜色ColorOverLifetime-速度颜色ColorBySpeed

几款实用软件分享

个人博客系统毕业设计开题报告

2021-05-07 constructor

图片存储--引用
随机推荐
2021-05-07 package inheritance super this
NOI OJ 1.2 10:Hello, World! Size of C language
SQL教程之 5 个必须知道的用于操作日期的 SQL 函数
How does thymeleaf get the value of the request parameter in the URL?
炫酷相册代码,祝对象生日快乐!
NOI OJ 1.4 01:判断数正负 C语言
【软件与系统安全】堆溢出
2021-05-11抽象类
Build a QQ robot to wake up your girlfriend
新派科技美学、原生物联网操作系统重塑全屋智能
STM32F1与STM32CubeIDE编程实例-红外寻迹传感器驱动
NOI OJ 1.3 16:计算线段长度 C语言
What is JSX in the JS tutorial? Why do we need it?
MySQL-01. Summary of database optimization and explain field knowledge in work
Golang 快速上手 (3)
文件IO(1)
SPI与IIC异同
2021-04-27 classes and objects
Liujinhai, architect of zhongang Mining: lithium battery opens up a Xintiandi for fluorine chemical industry
File IO (1)