epoll

高效 I/O 多路复用

Linux Kernel's High-Performance Event Notification

O(1) × 高效 × 可扩展

基本概念

epoll 是 Linux 内核提供的高效 I/O 事件通知机制, 相比传统的 selectpoll,具有更好的性能和可扩展性。

O(1)
时间复杂度
百万级
连接支持
事件驱动
通知机制

核心优势

  • 高效性能
  • 内存友好
  • 边缘触发
  • 水平触发

性能对比

Performance Comparison

select/poll

  • • 时间复杂度: O(n)
  • • 文件描述符限制: 1024
  • • 每次调用需要拷贝整个集合

epoll

  • • 时间复杂度: O(1)
  • • 文件描述符限制: 无限制
  • • 只返回就绪的文件描述符

epoll_create

创建 epoll 实例

int epfd = epoll_create1(0);

epoll_ctl

控制 epoll 事件

epoll_ctl(epfd, EPOLL_CTL_ADD, 
          fd, &event);

epoll_wait

等待事件发生

int nfds = epoll_wait(epfd, 
    events, MAX_EVENTS, -1);

工作模式

Working Modes

LT 水平触发

Level Triggered

  • • 默认工作模式
  • • 只要缓冲区有数据就会触发
  • • 兼容传统的 select/poll
  • • 编程简单,不易出错
event.events = EPOLLIN;

ET 边缘触发

Edge Triggered

  • • 高性能模式
  • • 只在状态变化时触发
  • • 需要一次性读完所有数据
  • • 通常配合非阻塞 I/O
event.events = EPOLLIN | EPOLLET;

完整实现示例

Complete Implementation
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#define MAX_EVENTS 1024
#define BUFFER_SIZE 1024

// 设置非阻塞模式
int set_nonblocking(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1) {
        perror("fcntl F_GETFL");
        return -1;
    }
    
    flags |= O_NONBLOCK;
    if (fcntl(fd, F_SETFL, flags) == -1) {
        perror("fcntl F_SETFL");
        return -1;
    }
    
    return 0;
}

int main() {
    int listen_fd, epoll_fd;
    struct sockaddr_in server_addr;
    struct epoll_event event, events[MAX_EVENTS];
    
    // 创建监听套接字
    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_fd == -1) {
        perror("socket");
        return -1;
    }
    
    // 设置地址重用
    int reuse = 1;
    setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    
    // 绑定地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(8080);
    
    if (bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind");
        close(listen_fd);
        return -1;
    }
    
    // 开始监听
    if (listen(listen_fd, SOMAXCONN) == -1) {
        perror("listen");
        close(listen_fd);
        return -1;
    }
    
    // 设置非阻塞模式
    if (set_nonblocking(listen_fd) == -1) {
        close(listen_fd);
        return -1;
    }
    
    // 创建 epoll 实例
    epoll_fd = epoll_create1(0);
    if (epoll_fd == -1) {
        perror("epoll_create1");
        close(listen_fd);
        return -1;
    }
    
    // 添加监听套接字到 epoll
    event.events = EPOLLIN | EPOLLET;  // 边缘触发模式
    event.data.fd = listen_fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &event) == -1) {
        perror("epoll_ctl: listen_fd");
        close(listen_fd);
        close(epoll_fd);
        return -1;
    }
    
    printf("服务器启动,监听端口 8080...\n");
    
    // 主事件循环
    while (1) {
        int nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
        if (nfds == -1) {
            perror("epoll_wait");
            break;
        }
        
        for (int i = 0; i < nfds; i++) {
            if (events[i].data.fd == listen_fd) {
                // 处理新连接
                struct sockaddr_in client_addr;
                socklen_t client_len = sizeof(client_addr);
                
                while (1) {
                    int client_fd = accept(listen_fd, 
                                         (struct sockaddr*)&client_addr, 
                                         &client_len);
                    if (client_fd == -1) {
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            // 没有更多连接了
                            break;
                        } else {
                            perror("accept");
                            break;
                        }
                    }
                    
                    printf("新连接: %s:%d\n", 
                           inet_ntoa(client_addr.sin_addr),
                           ntohs(client_addr.sin_port));
                    
                    // 设置客户端套接字为非阻塞
                    if (set_nonblocking(client_fd) == -1) {
                        close(client_fd);
                        continue;
                    }
                    
                    // 添加到 epoll
                    event.events = EPOLLIN | EPOLLET;
                    event.data.fd = client_fd;
                    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 
                                client_fd, &event) == -1) {
                        perror("epoll_ctl: client_fd");
                        close(client_fd);
                    }
                }
            } else {
                // 处理客户端数据
                int client_fd = events[i].data.fd;
                char buffer[BUFFER_SIZE];
                
                while (1) {
                    ssize_t bytes_read = read(client_fd, buffer, sizeof(buffer));
                    if (bytes_read == -1) {
                        if (errno == EAGAIN || errno == EWOULDBLOCK) {
                            // 数据读完了
                            break;
                        } else {
                            perror("read");
                            epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client_fd, NULL);
                            close(client_fd);
                            break;
                        }
                    } else if (bytes_read == 0) {
                        // 客户端关闭连接
                        printf("客户端断开连接: fd=%d\n", client_fd);
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client_fd, NULL);
                        close(client_fd);
                        break;
                    } else {
                        // 回显数据
                        write(client_fd, buffer, bytes_read);
                    }
                }
            }
        }
    }
    
    close(listen_fd);
    close(epoll_fd);
    return 0;
}

高级用法

EPOLLONESHOT

一次性事件,触发后自动移除

EPOLLEXCLUSIVE

避免惊群效应,只唤醒一个进程

自定义数据

使用 event.data.ptr 传递自定义结构

注意事项

ET 模式必须使用非阻塞 I/O

ET 模式需要循环读取直到 EAGAIN

关闭文件描述符会自动从 epoll 中移除

epoll 实例本身也是文件描述符

总结

epoll 是 Linux 下高性能网络编程的首选方案

高性能

O(1) 时间复杂度,支持百万级并发连接

灵活性

支持 LT 和 ET 两种工作模式

易用性

简洁的 API 设计,功能强大