一、poll机制的作用
1.poll机制的作用
在前面的使用中断的的方式来读取按键值(linux 中断管理(四))。使用这种方式读取按键,如果按键没有按下的时候,应用程序会一直处于睡眠的状态。如果想要即使按键没有按下,在一定的时间后也能返回,要实现这种功能,可以使用poll机制。(select IO复用和epoll也可以实现这种功能,这里只讲poll机制)
二、poll机制的应用编程
1.应用层函数接口
1).API:
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
2).Paramet:
fds
nfds
timeout
参数类型:
struct pollfd {
int fd; /* 文件描述符 /
short events; / 等待的发生事件类型 /
short revents; / 实际返回的事件类型 */
};
参数描述:
fds是一个结构体指针,也就是poll函数可以同时等待一个或者多个文件描述符的事件
参数类型:
nfds_t,其实就是int型
参数描述:
用来说明poll同时监听fds的个数
参数类型:
int
参数描述:
等于-1:永久等待
等于0:立即返回
大于0:等待超时时间,以毫秒为单位
3).Return:
返回值
描述
<0
错误返回
=0
超时返回
>0
返回结构体中 revents 域不为 0 的文件描述符个数
2.应用程序
应用程序主要使用poll的方式读取按键的值,并且设置5000ms超时等待
#include
#include
#include
#include
#include
/* poll机制测试
*/
int main(int argc, char **argv)
{
int fd;
unsigned char key_val;
int ret;
/* 定义一个 struct pollfd 结构体数组*/
struct pollfd fds[1];
/* 打开一个设备文件 */
fd = open("/dev/my_button", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
/**************** 初始化 struct pollfd 结构体 *************/
/* 初始化文件描述符 */
fds[0].fd = fd;