epoll分析

本文主要从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)

在有事件发生时被唤醒,并将就绪队列中的事件返回给用户。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值