Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核調試技術之自構 proc

在內核中,printk 可將訊息寫入 log_buf,使用者可透過 /proc/kmsg 讀取。本文以自構 mymsg 為例,說明如何建立自訂 proc 入口,讓內核訊息能被使用者空間讀取。

proc 入口概念

內核透過 create_proc_entry 建立 /proc 檔案,並以 file_operations 指定 open、read 等回呼。當使用者執行 cat /proc/mymsg 時,便會觸發 mymsg_read。

環形佇列

mymsg 使用環形佇列保存訊息。head 指向可讀位置,tail 指向可寫位置;當尾端追上頭端時表示已滿,頭端追上尾端時表示為空。

static int is_mylog_empty(void) {
    return mylog_r == mylog_w;
}
static int is_mylog_full(void) {
    return (mylog_w + 1) % MYLOG_BUF_LEN == mylog_r;
}

讀取與休眠

mymsg_read 會先判斷是否非阻塞,若無資料可讀,可透過 wait_event_interruptible 進入休眠;當 mylog_putc 寫入資料後,再以 wake_up_interruptible 喚醒等待進程。

static ssize_t mymsg_read(struct file *file, char __user *buf,
    size_t count, loff_t *ppos) {
    char c;
    size_t i = 0;
    wait_event_interruptible(mymsg_waitq, !is_mylog_empty_for_read());
    while (mylog_getc(& c) && i < count) {
        __put_user(c, buf);
        buf++;
        i++;
    }
    return i;
}

最後以 create_proc_entry 建立 mymsg,並在 mymsg_init 中掛載 proc_mymsg_operations,即可在核心空間輸出訊息並由使用者空間讀取。

Copyright © Linux教程網 All Rights Reserved