epoll源码探秘(epoll_create)

epoll_create是epoll系列的核心函数,用于创建epoll句柄,并占用一个fd值。在Linux 2.6.8以后,size参数不再使用。函数内部包括ep_alloc()的调用,用于初始化epoll结构:文件等待队列、唤醒队列、就绪队列、红黑树等。此外,还会通过get_unused_fd_flags()获取文件描述符,anon_inode_getfile()创建匿名文件,最后fd_install()安装文件与fd的关系。
摘要由CSDN通过智能技术生成

epoll源码探秘(epoll_create)

epoll系列的系统函数,很简单,但是很强大。epoll_create(),epoll_ctl() , epoll_wait(),三个就够了。

一些重要的结构:

/*
 * Each file descriptor added to the eventpoll interface will
 * have an entry of this type linked to the "rbr" RB tree.
 * Avoid increasing the size of this struct, there can be many thousands
 * of these on a server and we do not want this to take another cache line.(红黑树单节点)
 */
struct epitem {
	union {
		/* RB tree node links this structure to the eventpoll RB tree */
		struct rb_node rbn;
		/* Used to free the struct epitem */
		struct rcu_head rcu;
	};

	/* List header used to link this structure to the eventpoll ready list (列表头用于连接结构的eventpoll就绪列表)*/
	struct list_head rdllink;

	/*
	 * Works together "struct eventpoll"->ovflist in keeping the
	 * single linked chain of items.
	 */
	struct epitem *next;

	/* The file descriptor information this item refers to (关联的文件描述符)*/
	struct epoll_filefd ffd;

	/* Number of active wait queue attached to poll operations (轮询操作)*/
	int nwait;

	/* List containing poll wait queues */
	struct list_head pwqlist;

	/* The "container" of this item */
	struct eventpoll *ep;

	/* List header used to link this item to the "struct file" items list */
	struct list_head fllink;
`epoll_create` 和 `epoll_create1` 都是 Linux 系统中的用于创建 epoll 实例的系统调用。它们的主要区别在于: 1. **兼容性**: - `epoll_create` 是早期版本的 epoll 创建函数,在 Linux 2.6 内核之前存在,需要手动设置一些标志位,如 EPOLL_CLOEXEC 来控制文件描述符的行为。 - `epoll_create1` 是引入在内核 2.6.19 版本之后,它提供了一个更现代、简洁的接口,可以一次性指定更多的选项。 2. **功能参数**: - `epoll_create` 需要传递一个整数参数,表示最大事件数量。如果超过这个限制,可能会失败。 - `epoll_create1` 可以直接传入一个标志位(EPOLL_CLOEXEC 或 EPOLL_LEVEL | EPOLL_ONESHOT),使得创建出来的 epoll 文件描述符默认关闭(仅适用于新式系统)。 3. **错误处理**: - `epoll_create` 的错误处理相对复杂,因为它不带错误检查。 - `epoll_create1` 更明确地返回 -1 并设置errno来指示错误,比如当参数无效或者资源不足时。 4. **安全性与便利性**: - `epoll_create1` 提供了更好的错误处理机制,同时也简化了一些安全选项的设置,使得使用更为方便。 总的来说,`epoll_create1` 是对 `epoll_create` 的改进,建议在支持该函数的新系统上优先选择,因为它提供了一种更加现代的方式来处理事件监听。如果你的项目需要兼容较旧的Linux版本,或者需要更详细的错误处理,那么 `epoll_create` 仍可能是必要的。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值