【Linux】从零开始使用多路转接IO --- epoll
从零开始认识多路转接
- 1 epoll的作用和定位
- 2 epoll 的接口
- 3 epoll工作原理
- 4 实现epollserverV1
1 epoll的作用和定位
之前提过的多路转接方案select和poll 都有致命缺点:底层都是暴力的遍历,效率不高!
对此,诞生出了epoll这个更好的方案!
按照 man 手册的说法: 是为处理大批量句柄而作了改进的 poll。它是在 2.5.44 内核中被引进的(epoll(4) is a new API introduced in Linux kernel 2.5.44)。它几乎具备了之前所说的一切优点, 被公认为 Linux2.6 下性能最好的多路 I/O 就绪通知方法.
2 epoll 的接口
epoll的相关接口有三个:
epoll_create
EPOLL_CREATE(2) Linux Programmer's Manual EPOLL_CREATE(2)
NAME
epoll_create, epoll_create1 - open an epoll file descriptor
SYNOPSIS
#include
int epoll_create(int size);
int epoll_create1(int flags);
epoll_create接口只有一个参数,其功能是在内核创建一个epoll模型!这个模型我们后面详细谈。这个size我们只有设置为一个大于零的数即可。创建成功之后会给我们返回一个文件描述符,现在我们还理解不了,后续讲解。
epoll_ctl
EPOLL_CTL(2) Linux Programmer's Manual EPOLL_CTL(2)
NAME
epoll_ctl - control interface for an epoll file descriptor
SYNOPSIS
#include
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
DESCRIPTION
This system call is used to add, modify, or remove entries in the interest list of the epoll(7) instance referred to by the file descriptor epfd. It requests that
the operation op be performed for the target file descriptor, fd.
epoll_ctl有四个参数:
- int epfd:这个就是通过epoll_create获得的文件描述符
- int op:这个是操作选项,我们这个函数共用三种选项:
EPOLL_CTL_ADD
增加EPOLL_CTL_MOD
修改EPOLL_CTL_DEL
删除。 - int fd:对这个文件描述符进行操作。
- struct epoll_event * event:这时一个结构体,类似struct pollfd,但内部更加复杂:
其中的events位图就可以设置读事件,写事件…注意这里没有返回事件!typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */ };
epoll_wait
EPOLL_WAIT(2) Linux Programmer's Manual EPOLL_WAIT(2)
NAME
epoll_wait, epoll_pwait - wait for an I/O event on an epoll file descriptor
SYNOPSIS
#include
int epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout);
int epoll_pwait(int epfd, struct epoll_event *events,
int maxevents, int timeout,
const sigset_t *sigmask);
DESCRIPTION
The epoll_wait