萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 核心驅動 fasync 非同步通知機制圖解與實作指南

一、Linux I/O 模型四象限

阻塞非阻塞
同步同步阻塞 I/O (預設 read/write)同步非阻塞 I/O (O_NONBLOCK)
非同步非同步阻塞 I/O (較少見)非同步非阻塞 I/O (AIO, fasync/SIGIO)
  • 同步:應用程式主動呼叫函數,函數回傳時已獲得結果。
  • 非同步:應用程式發起請求後繼續執行,資料就緒時由核心主動通知(訊號/回呼)。
  • 阻塞:等待資料時行程睡眠;非阻塞:立即回傳,應用自行輪詢或處理其他任務。

二、fasync (SIGIO) 機制架構

fasync 核心流程圖

(建議下載原圖放大檢視)

三、核心資料結構

/* include/linux/fs.h */
struct fasync_struct {
    int magic;
    int fa_fd;                    // 檔案描述符
    struct fasync_struct *fa_next; // 鏈表下一節點
    struct file *fa_file;         // 對應的 file 結構
    struct rcu_head fa_rcu;
};

每個 struct file 持有一個 struct fasync_struct *f_fasync 指標,指向該檔案所有註冊非同步通知的行程鏈表。

四、應用程式端實作步驟

  1. 安裝 SIGIO 訊號處理器:
    void sigio_handler(int signo) {
        // 資料可讀/可寫,執行非阻塞 read/write
    }
    signal(SIGIO, sigio_handler);
  2. 設定進程/進程組 ID 接收訊號:
    fcntl(fd, F_SETOWN, getpid()); // 或設定負值表示進程組
  3. 啟用 FASYNC 旗標:
    int flags = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, flags | FASYNC);

    此呼叫會觸發驅動程式的 fasync() file_operation,將當前行程加入 f_fasync 鏈表。

五、驅動程式端實作要點

  1. 定義 fasync_struct 指標:
    static struct fasync_struct *my_fasync_queue = NULL;
  2. 實作 file_operations.fasync:
    static int my_fasync(int fd, struct file *filp, int on) {
        return fasync_helper(fd, filp, on, &my_fasync_queue);
    }

    fasync_helper() 核心輔助函數自動處理鏈表增刪。

  3. 資料就緒時發送訊號:
    // 在中斷處理常式、poll_wakeup、資料到達等路徑呼叫
    kill_fasync(&my_fasync_queue, SIGIO, POLL_IN); // 可讀
    // 或 POLL_OUT (可寫), POLL_ERR, POLL_PRI 等

六、完整驅動程式片段

/* 字元裝置驅動範例 */
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/poll.h>

#define DEV_NAME "fasync_demo"

static struct fasync_struct *async_queue;
static char kernel_buf[1024];
static int buf_len;

static int demo_open(struct inode *inode, struct file *filp) { return 0; }
static int demo_release(struct inode *inode, struct file *filp) {
    fasync_helper(-1, filp, 0, &async_queue); // 移除註冊
    return 0;
}

static ssize_t demo_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) {
    if (buf_len == 0) return 0;
    count = min(count, (size_t)buf_len);
    if (copy_to_user(buf, kernel_buf, count)) return -EFAULT;
    memmove(kernel_buf, kernel_buf + count, buf_len - count);
    buf_len -= count;
    return count;
}

static ssize_t demo_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) {
    count = min(count, sizeof(kernel_buf) - buf_len);
    if (copy_from_user(kernel_buf + buf_len, buf, count)) return -EFAULT;
    buf_len += count;
    kill_fasync(&async_queue, SIGIO, POLL_IN); // 通知應用層可讀
    return count;
}

static int demo_fasync(int fd, struct file *filp, int on) {
    return fasync_helper(fd, filp, on, &async_queue);
}

static struct file_operations fops = {
    .owner = THIS_MODULE,
    .read = demo_read,
    .write = demo_write,
    .fasync = demo_fasync,
    .open = demo_open,
    .release = demo_release,
};

/* 模組初始化/註冊省略 */

七、應用程式測試程式

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

#define DEV "/dev/fasync_demo"

volatile sig_atomic_t data_ready = 0;

void sigio_handler(int sig) { data_ready = 1; }

int main() {
    int fd = open(DEV, O_RDWR);
    if (fd < 0) { perror("open"); exit(1); }

    signal(SIGIO, sigio_handler);
    fcntl(fd, F_SETOWN, getpid());
    int flags = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, flags | FASYNC);

    printf("Waiting for data (press Ctrl+C to exit)...\n");
    while (1) {
        if (data_ready) {
            data_ready = 0;
            char buf[128];
            int n = read(fd, buf, sizeof(buf));
            if (n > 0) {
                buf[n] = '\0';
                printf("Received: %s\n", buf);
            }
        }
        pause(); // 睡眠等待訊號
    }
    close(fd);
    return 0;
}

八、關鍵特性與限制

  • 非真正的 Session Copy:本質是共享 Socket/檔案描述符,首次連線建立 Unix domain socket 檔案(ControlPath),後續連線複用該 socket。
  • 訊號驅動:依賴 SIGIO,非阻塞喚醒機制。
  • 單行程限制:同一檔案描述符同一時間只能有一個行程接收 SIGIO(F_SETOWN 決定)。
  • 邊緣觸發:資料到達發送一次訊號,應用必須循環讀取直到 EAGAIN,否則會遺漏後續資料。
  • 主行程退出影響:若建立 fasync 的主行程強制結束,共享 socket 關閉,其他複用連線會被迫斷開。

九、現代替代方案

  • epoll/kqueue/IO_uring:高效能 I/O 多工,無訊號開銷,支援大量並發。
  • Linux AIO (io_submit/io_getevents):真正的非同步 I/O,適用於直接 I/O (O_DIRECT) 場景。
  • signalfd + epoll:將訊號轉為檔案描述符,整合進事件迴圈。
copyright © 萬盛學電腦網 all rights reserved