proc檔案系統
/proc 目錄就是Linux的proc檔案系統了, 這裡面存放核心的配置資訊, 網路設定系統, 以及進程的狀態都是以pid明明的目錄。總之, 關於核心的基本配置你就可以找到。 核心更新
在核心的迭代過程中,總有一些介面被廢棄, create_proc_entry就是其中之一。
依稀記得,去年的時候一直想寫個proc檔案系統測試下, 直到上個月才有時間來做這個事情。當初讓我試了就不測試的原因就是那個create_proc_entry函數的棄用, 網上能搜尋的例子基本都是用這個函數。 範例代碼
#include <linux/module.h>#include <linux/proc_fs.h>#include <linux/seq_file.h>#include <asm/uaccess.h>#include <linux/slab.h>static char *buffer = NULL;static int hello_proc_show(struct seq_file *m, void *v) { seq_printf(m, "Hello proc!\n"); seq_printf(m, "buffer=%s\n", buffer); int i = 0; if (buffer != NULL) { if (buffer[0] == 's') { for (i = 0; i < 10; i++) seq_printf(m, "i = %d\n", i); } } return 0;}static ssize_t hello_proc_write(struct file *file, const char *buffer, size_t len, loff_t *off){ int user_len = 0; user_len = len; buffer = (char *)kmalloc(user_len+1, GFP_KERNEL); memset(buffer, 0, user_len + 1); if (copy_from_user(buffer, buffer, user_len)) { printk( "hello_proc error\n"); return -EFAULT; } printk( "userlen=%d\n", user_len); return user_len;}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, .write = hello_proc_write, .llseek = seq_lseek, .release = single_release,};static int __init hello_proc_init(void) { proc_create("hello_proc", 0666, NULL, &hello_proc_fops); return 0;}static void __exit hello_proc_exit(void) { remove_proc_entry("hello_proc", NULL);}MODULE_LICENSE("GPL");module_init(hello_proc_init);module_exit(hello_proc_exit);
範例代碼注釋
功能: 其在/proc目錄下建立了hello_proc檔案,
echo s >/proc/hello_proccat /proc/hello_proc這樣就會有輸出資訊了。
seq_file 是核心提供的序列介面, 詳情就不介紹了,這種方式當資料大的時候記憶體配置不需要你去關心, 非常實用。
源碼地址:qianguozheng