本文主要从epoll
的三个主要调用epoll_create, epoll_ctl, epoll_wait
进行分析
1.epoll_create
1.1 使用方式
int epoll_create(int size)
创建一个epoll
的文件描述符。
1.2 源码分析
//epoll_create的源码,主要做的事情是创建一个eventpoll和file结构体。
//eventpoll结构体中主要成员有事件的就绪队列和一棵红黑树,红黑树管理的就是监听的文件描述符。
SYSCALL_DEFINE1(epoll_create1, int, flags)
{
int error;
struct eventpoll *ep = NULL;
/* Check the EPOLL_* constant for consistency. */
BUILD_BUG_ON(EPOLL_CLOEXEC != O_CLOEXEC);
if (flags & ~EPOLL_CLOEXEC)
return -EINVAL;
/*
* Create the internal data structure ("struct eventpoll").
*/
error = ep_alloc(&ep);
if (error < 0)
return error;
/*
* Creates all the items needed to setup an eventpoll file. That is,
* a file structure and a free file descriptor.
*/
error = anon_inode_getfd("[eventpoll]", &eventpoll_fops, ep,
O_RDWR | (flags & O_CLOEXEC));
if (error < 0)
ep_free(ep);
return error;
}
struct eventpoll {
/* Protect the this structure access */
spinlock_t lock;
/*
* This mutex is used to ensure that files are not removed
* while epoll is using them. This is held during the event
* collection loop, the file cleanup path, the epoll file exit
* code and the ctl operations.
*/
struct mutex mtx;
/* Wait queue used by sys_epoll_wait() */
wait_queue_head_t wq;
/* Wait queue used by file->poll() */
wait_queue_head_t poll_wait;
/* List of ready file descriptors 就绪队列,其中是就绪的文件描述符*/
struct list_head rdllist;
/* RB tree root used to store monitored fd structs 其中是epoll监听的文件描述符*/
struct rb_root rbr;
/*
* This is a single linked list that chains all the "struct epitem" that
* happened while transfering ready events to userspace w/out
* holding ->lock.
*/
struct epitem *ovflist;
/* The user that created the eventpoll descriptor */
struct user_struct *user;
};
2. epoll_ctl
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
其中op
表示做什么操作,有EPOLL_CTL_ADD、EPOLL_CTL_MOD、 EPOLL_CTL_DEL
三个操作。如果是EPOLL_CTL_ADD
的话,主要做的事为:
将监听的文件描述符加入红黑树,并注册回调函数。回调函数做的事情为当事件发生时,将对应的文件描述符加入到就绪队列中。
3. epoll_wait
int epoll_wait(int epfd, epoll_event events, int max events, int timeout)
在有事件发生时被唤醒,并将就绪队列中的事件返回给用户。