1、Linux epoll函数
1.1、创建epoll实例
int epoll_create1(int flag);
返回值:-1 失败,非负数 成功
flag :默认传入0
1.2、管理epoll对象
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
epfd :epoll 对象文件句柄
op :epoll操作动作,添加,修改,删除
fd :需要轮询的文件句柄
event :需要监听的epoll事件
1.3、等待epoll事件
int epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout);
epfd :epoll 对象文件句柄
events :epoll事件上报
maxevents : 最大处理epoll事件数量
timeout : 超时时间
2、函数实例
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <string.h>
#define MAX_EVENT 1
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 mEpollFd;
int ret;
struct input_event event;
struct epoll_event ep_event;
struct epoll_event pending_event[MAX_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]);
}
/*创建EpollFd*/
mEpollFd = epoll_create1(0);
if(mEpollFd <0){
printf("epoll create err = %s \n", strerror(errno));
} else {
printf("epoll create success \n");
}
/*添加监听*/
ep_event.events = EPOLLIN;
ep_event.data.fd = fd;
ret = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &ep_event);
if(ret < 0){
printf("epoll_ctl err = %s \n", strerror(errno));
} else {
printf("epoll_ctl success \n");
}
/*等待文件字符变化*/
while(1){
ret = epoll_wait(mEpollFd, pending_event, MAX_EVENT, 5);
if(ret > 0){
if(pending_event[0].data.fd == fd){
if (pending_event[0].events & EPOLLIN) {
while(read(fd, &event, sizeof(event)) == sizeof(event)){
printf("epoll get event: type =0x%x, Code = 0x%x value = 0x%x \n",event.type, event.code, event.value);
printf("epoll get event: type = %s, Code = %s value = 0x%x \n",eventTypeToString(event.type), eventCodeToString(event.code), event.value);
}
}
}
} else if (ret == 0){
//printf("epoll_wait time out \n");
} else {
perror("epoll_wait error \n");
}
}
return 0;
}
3、代码运行效果
编译二进制文件,运行到手机端