Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux I/O 多路複用(一):epoll 的 API 與 echo 伺服器實作

一、epoll 是什麼

epoll() 是 Linux 特有的 I/O 多路複用機制,無論介面還是實作方式,都與 select()、poll() 有明顯差異。select/poll 每次呼叫都得把要監聽的 fd 集合整包傳進核心,epoll 則把 fd 放進核心的事件表,只需一個額外的 fd 來標識這張表,後續的等待不必再重複傳遞。

需要掌握的三個 API:

int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);

以及兩個結構:

typedef union epoll_data {
    void *ptr;
    int fd;          // 實務上最常使用這個
    uint32_t u32;
    uint64_t u64;
} epoll_data_t;

struct epoll_event {
    uint32_t     events;   /* 事件遮罩 */
    epoll_data_t data;     /* 使用者自訂資料 */
};

二、epoll_wait 的關鍵理解

(1)回傳值:事件表中已就緒的客戶端數量。
(2)events 參數:核心會把就緒客戶端的資訊填進這個陣列。
(3)timeout:填 -1 表示永久等待,填 0 表示立刻返回(輪詢),填正數則是毫秒數。

三、核心思想

建立一張核心事件表,存放被監聽的 socket 與感興趣的事件;用 epoll_wait 找出就緒的 socket;用 epoll_ctl 進行增加(EPOLL_CTL_ADD)、刪除(EPOLL_CTL_DEL)、修改(EPOLL_CTL_MOD),搭配 EPOLLIN / EPOLLOUT 等巨集使用。

四、程式碼實作

utili.h

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <assert.h>
#include <sys/select.h>
#include <poll.h>
#include <sys/epoll.h>

#define SERVER_IP     "127.0.0.1"
#define SERVER_PORT   8787
#define LISTEN_QUEUE  5
#define BUFFER_SIZE   256
#define OPEN_MAX      1000
#define FDSIZE        1000
#define EPOLLEVENTS   100

ser.c

#include "../utili.h"

static int socket_bind(const char *ip, int port) {
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addrSer;
    addrSer.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &addrSer.sin_addr);
    addrSer.sin_port = htons(port);
    bind(listenfd, (struct sockaddr*)&addrSer, sizeof(struct sockaddr));
    return listenfd;
}

static void add_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
}

static void delete_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &ev);
}

static void modify_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ev);
}

static void handle_accept(int epollfd, int listenfd) {
    struct sockaddr_in addrCli;
    socklen_t len = sizeof(struct sockaddr);
    int clifd = accept(listenfd, (struct sockaddr*)&addrCli, &len);
    if (clifd != -1)
        add_event(epollfd, clifd, EPOLLIN);
}

static void do_read(int epollfd, int fd, char *buf) {
    int nread = read(fd, buf, BUFFER_SIZE);
    if (nread <= 0) {
        close(fd);
        delete_event(epollfd, fd, EPOLLIN);
    } else {
        printf("read msg:>%s\n", buf);
        modify_event(epollfd, fd, EPOLLOUT);   // 讀完改監聽可寫
    }
}

static void do_write(int epollfd, int fd, char *buf) {
    int nwrite = write(fd, buf, strlen(buf) + 1);
    if (nwrite == -1) {
        close(fd);
        delete_event(epollfd, fd, EPOLLOUT);
    } else {
        modify_event(epollfd, fd, EPOLLIN);    // 寫完改回監聽可讀
    }
    memset(buf, 0, BUFFER_SIZE);
}

static void handle_events(int epollfd, struct epoll_event *events,
                          int num, int listenfd, char *buf) {
    for (int i = 0; i < num; ++i) {
        int fd = events[i].data.fd;
        if (fd == listenfd && (events[i].events & EPOLLIN))
            handle_accept(epollfd, listenfd);
        else if (events[i].events & EPOLLIN)
            do_read(epollfd, fd, buf);
        else if (events[i].events & EPOLLOUT)
            do_write(epollfd, fd, buf);
    }
}

static void do_epoll(int listenfd) {
    char buffer[BUFFER_SIZE];
    struct epoll_event events[EPOLLEVENTS];
    int epollfd = epoll_create(FDSIZE);
    add_event(epollfd, listenfd, EPOLLIN);
    for (;;) {
        int ret = epoll_wait(epollfd, events, EPOLLEVENTS, -1);
        handle_events(epollfd, events, ret, listenfd, buffer);
    }
    close(epollfd);
}

int main(void) {
    int listenfd = socket_bind(SERVER_IP, SERVER_PORT);
    listen(listenfd, LISTEN_QUEUE);
    do_epoll(listenfd);
    return 0;
}

cli.c

#include "../utili.h"

static void add_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
}
static void delete_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &ev);
}
static void modify_event(int epollfd, int fd, int state) {
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ev);
}

static void do_read(int epollfd, int fd, int sockfd, char *buf) {
    int nread = read(fd, buf, BUFFER_SIZE);
    if (nread <= 0) {
        if (fd != STDIN_FILENO) { close(fd); delete_event(epollfd, fd, EPOLLIN); }
    } else if (fd == STDIN_FILENO) {
        add_event(epollfd, sockfd, EPOLLOUT);          // 輸入完成,準備送出
    } else {
        delete_event(epollfd, fd, EPOLLIN);
        add_event(epollfd, STDOUT_FILENO, EPOLLOUT);   // 轉貼到螢幕
        printf("Ser :>%s", buf);
    }
}

static void do_write(int epollfd, int fd, int sockfd, char *buf) {
    int nwrite = write(fd, buf, strlen(buf) + 1);
    if (nwrite == -1) {
        perror("write");
        if (fd != STDOUT_FILENO) close(fd);
    } else if (fd == STDOUT_FILENO) {
        delete_event(epollfd, fd, EPOLLOUT);
    } else {
        modify_event(epollfd, sockfd, EPOLLIN);
    }
    memset(buf, 0, BUFFER_SIZE);
}

static void handle_events(int epollfd, struct epoll_event *events,
                          int num, int sockfd, char *buf) {
    for (int i = 0; i < num; ++i) {
        int fd = events[i].data.fd;
        if (events[i].events & EPOLLIN)       do_read(epollfd, fd, sockfd, buf);
        else if (events[i].events & EPOLLOUT) do_write(epollfd, fd, sockfd, buf);
    }
}

static void handle_connection(int sockfd) {
    struct epoll_event events[EPOLLEVENTS];
    int epollfd = epoll_create(FDSIZE);
    add_event(epollfd, STDIN_FILENO, EPOLLIN);
    char buffer[BUFFER_SIZE];
    for (;;) {
        int ret = epoll_wait(epollfd, events, EPOLLEVENTS, -1);
        handle_events(epollfd, events, ret, sockfd, buffer);
    }
    close(epollfd);
}

int main(void) {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addrSer;
    addrSer.sin_family = AF_INET;
    addrSer.sin_port = htons(SERVER_PORT);
    addrSer.sin_addr.s_addr = inet_addr(SERVER_IP);
    connect(sockfd, (struct sockaddr*)&addrSer, sizeof(struct sockaddr));
    handle_connection(sockfd);
    close(sockfd);
    return 0;
}

五、執行結果

伺服器端持續等待客戶端連入。兩個客戶端可各自輸入訊息,伺服器原封不動回傳。

Linux I/O 多路複用(一):epoll 的 API 與 echo 伺服器實作 Linux I/O 多路複用(一):epoll 的 API 與 echo 伺服器實作

epoll 最大的好處是不必逐一輪詢每個 socket,只回傳真正就緒的那些,客戶端數量上升時效率差距會非常明顯。實務上還要注意兩點:一是 read 回傳 0 代表對端關閉連線,必須把 fd 從事件表移除,否則 epoll_wait 會不斷對同一個 fd 回報事件而陷入忙迴圈;二是若改用邊緣觸發(EPOLLET),就必須把 read/write 寫成迴圈直到回傳 EAGAIN,並把 socket 設為非阻她又用,兩者要成套使用。

Copyright © Linux教程網 All Rights Reserved