epoll
是 Linux 内核为处理大批量文件描述符而作了改进的 select
和 poll
的增强版本。它提供了更高效的事件通知机制,特别适用于高并发网络编程。epoll
使用了“事件驱动”的方式,当有事件发生时,内核会立即通知应用程序,而不是像 select
和 poll
那样需要应用程序不断轮询。
epoll
在处理大量并发连接时,性能远优于 select
和 poll
。epoll
没有 select
中的文件描述符数量的硬性限制。epoll_wait
就会持续通知。以下是一个简单的 epoll
使用示例:
#include <sys/epoll.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int epfd = epoll_create(1); // 创建 epoll 实例
if (epfd == -1) {
perror("epoll_create");
return 1;
}
int fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
close(epfd);
return 1;
}
struct epoll_event event;
event.events = EPOLLIN; // 监听可读事件
event.data.fd = fd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event) == -1) {
perror("epoll_ctl: add");
close(fd);
close(epfd);
return 1;
}
struct epoll_event events[10];
int nfds = epoll_wait(epfd, events, 10, -1); // 等待事件发生
if (nfds == -1) {
perror("epoll_wait");
close(fd);
close(epfd);
return 1;
}
for (int i = 0; i < nfds; i++) {
if (events[i].events & EPOLLIN) {
printf("File descriptor %d is ready for reading.\n", events[i].data.fd);
}
}
close(fd);
close(epfd);
return 0;
}
问题1:epoll_wait
没有返回任何事件
epoll_ctl
中设置的 events
字段是否正确,并确保文件描述符确实有数据可读或可写。问题2:在高并发下性能不佳
通过以上信息,你应该能对 Linux 2.4 中的 epoll
有一个全面的了解,并能在实际开发中有效地应用它。
领取专属 10元无门槛券
手把手带您无忧上云