Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C 語言 Socket 編程:以 mio 抽象層切換 select/poll/epoll

一直想整理一篇關於網路編程模型的筆記,這篇就是。socket 對每個看這篇文章的人都不陌生,而選 IO 策略時,select、poll、epoll 是常見的三個選項。本文不討論「該選哪一個」,而是示範如何用巨集把策略做成可替換的配置。以下以 epoll 作為實作基礎(可參考〈epoll 的使用〉:https://www.linuxidc.com/Linux/2012-09/71142.htm)。

一、檔案結構

這個模型拆成幾個檔案,各司其職:

  • mio.c / mio.h:定義 mio_st 結構,並宣告建立新 mio_st 的方法。
  • mio_impl.h:模型的主要實作檔,多數操作都從這裡觸發。
  • mio_select.h / mio_select.c:select 策略實作,含相關巨集。
  • mio_poll.h / mio_poll.c:poll 策略實作。
  • mio_epoll.h / mio_epoll.c:epoll 策略實作。

換言之,同一份介面搭配三種底層實作,編譯時決定用哪一種。

二、抽象 IO 管理結構

mio_st 負責管理 IO 的全生命週期:建立監聽、建立連接、註冊既有 fd、註冊回呼、關閉、讀寫,以及進入事件迴圈。

typedef struct mio_st
{
    void (*mio_free)(struct mio_st **m);

    struct mio_fd_st *(*mio_listen)(struct mio_st **m, int port, char *sourceip,
                                    mio_handler_t app, void *arg);

    struct mio_fd_st *(*mio_connect)(struct mio_st **m, int port, char *hostip,
                                     mio_handler_t app, void *arg);

    struct mio_fd_st *(*mio_register)(struct mio_st **m, int fd,
                                      mio_handler_t app, void *arg);

    void (*mio_app)(struct mio_st **m, struct mio_fd_st *fd,
                    mio_handler_t app, void *arg);

    void (*mio_close)(struct mio_st **m, struct mio_fd_st *fd);

    void (*mio_write)(struct mio_st **m, struct mio_fd_st *fd);

    void (*mio_read)(struct mio_st **m, struct mio_fd_st *fd);

    void (*mio_run)(struct mio_st **m, int timeout);
} **mio_t;

每個成員都是函式指標,由具體策略的實作檔填入。上層程式只認 mio_t,完全不必知道底層是 select 還是 epoll。

連接本身的描述符則包在 mio_fd_st 裡:

typedef struct mio_fd_st
{
    int fd;
} *mio_fd_t;

最後把「事件類型」與「處理函式」也抽象出來:

typedef enum { action_ACCEPT, action_READ, action_WRITE, action_CLOSE } mio_action_t;
typedef int (*mio_handler_t) (struct mio_st **m, mio_action_t a, struct mio_fd_st *fd, void* data, void *arg);

枚舉對應「接受連線、讀資料、寫資料、關閉連線」四類動作;函式指標則是這些動作發生時要呼叫的處理器。應用層只要實作一個 handler,就能在四種事件上寫自己的邏輯,而底層策略可以隨時替換——這正是把 IO 模型抽象化的最大收益。

Copyright © Linux教程網 All Rights Reserved