1、Linux poll 函数
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
fds: 需要轮询的fd集合
nfds:需要轮询的fds数量
timeout:超时时间
返回值:0 超时,<0 发生异常,> 0 存在数据变化
2、函数用例
#include <poll.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <unistd.h>
static char * eventTypeToString(__u16 type){
switch(type){
case EV_SYN:
return "EV_SYN";
case EV_KEY:
return "EV_KEY";
case EV_REL:
return "EV_REL";
case EV_ABS:
return "EV_ABS";
case EV_MSC:
return "EV_MSC";
case EV_SW:
return "EV_SW";
default:
return "UNKOWN";
}
}
static char * eventCodeToString(__u16 code){
switch(code){
case KEY_ESC:
return "KEY_ESC";
case KEY_POWER:
return "KEY_POWER";
default:
return "UNKOWN";
}
}
int main (int argc, char ** argv){
int fd;
int err;
int len;
/*需要轮询的fds*/
struct pollfd fds[1];
/*需要轮询的fds数量*/
nfds_t nfds = 1;
struct input_event event;
if(argc != 2){
printf("Usage: %s <dev> \n", argv[0]);
}
fd = open(argv[1], O_RDWR | O_NONBLOCK);
if(fd < 0){
printf("open %s err \n", argv[1]);
} else {
printf("open %s success \n",argv[1]);
}
while(1){
fds[0].fd = fd;
fds[0].events = POLLIN;
fds[0].revents = 0;
int ret = poll(fds,nfds,5000);
printf("ret = %d \n", ret);
if(ret > 0){
if(fds[0].revents == POLLIN){
while(read(fd, &event, sizeof(event)) == sizeof(event)){
printf("get envent: type =0x%x, Code = 0x%x value = 0x%x",event.type, event.code, event.value);
}
}
} else if (ret == 0){
printf("time out \n");
} else {
perror("poll err \n");
}
}
return 0;
}
3、代码运行效果
编译二进制文件,运行到手机端