iT邦幫忙

DAY 16
1

Linux kernel模組的開發系列 第 16

/proc 檔案系統

在 Linux 中 /proc 檔案系統可以用來做為 kernel module 傳送訊息給程式之用,也能夠記錄一些 kernel 的狀態,如 /proc/modules 用以記錄 module 的內容、/proc/meminfo 用以記錄記憶體的狀態。

以下示範一個在 /proc 中建立檔案 (名為 hello_proc),當你 cat /proc/hello_proc 時會送出 Hello proc! 訊息。在這個範例中,proc_create 函數用以建立 /proc 檔案,remove_proc_entry 函數則會在卸載 module 時移除它。而關於這個 proc 檔案的設定,則定義在 hello_proc_fops 這個 file_operations 資料結構裡。

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static int hello_proc_show(struct seq_file *m, void *v) {
  seq_printf(m, "Hello proc!\n");
  return 0;
}

static int hello_proc_open(struct inode *inode, struct  file *file) {
  return single_open(file, hello_proc_show, NULL);
}

static const struct file_operations hello_proc_fops = {
  .owner = THIS_MODULE,
  .open = hello_proc_open,
  .read = seq_read,
  .llseek = seq_lseek,
  .release = single_release,
};

static int __init hello_proc_init(void) {
  proc_create("hello_proc", 0, NULL, &hello_proc_fops);
  return 0;
}

static void __exit hello_proc_exit(void) {
  remove_proc_entry("hello_proc", NULL);
}

上一篇
在 kernel 中移除 (反註冊) driver
下一篇
file_operations 資料結構
系列文
Linux kernel模組的開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言