在proc 目錄下建立檔案,不得不提到的struct file_operations , 詳細struct 資訊,可以查閱—— [linux kernel] .
本篇主要讨論的是以下幾個接口:

open
int (open) (struct inode , struct file *); //打開![]()
Linux學習筆記之proc檔案使用篇建立proc下檔案
實作test_proc_show function,這樣可以在shell 下輸入cat /proc/test傳回help 資訊、或者顯示你希望提供的資訊。
test_proc_show 函數:
static int test_proc_show(struct seq_file *m, void *v);
write
read/write 功能類似,write 相對較為複雜,這裡主要介紹下write。
static ssize_t test_proc_write(stuct file *file, const char *buf, size_t count, loff_t *f_ops);
write 使用有兩種方法:
- shell 下輸入echo X X > /proc/test
- 使用linux 提供的write接口。
第一個方法比較簡單,就不說了。主要說下第二個例子:
/* open file */
char * file = "/proc/test";
int fd = ;
fd = open(file, O_RDWR);
if (fd == -) {
prerror("open fail\n");
return NULL;
}
關于test_proc_write的功能編寫,與正常的function沒有差別,主要注意傳回值:
- 如果正常執行,請傳回count;如果無法用sscanf拿到預期的值,請再使用sscanf拿一次字元串,如果傳回值非0,請傳回count;如果傳回值為0,請傳回異常值。關于sscanf 請參考—— [Linux學習筆記之sscanf] .
- 如果異常執行,請傳回異常值。
建立proc下檔案
說了這麼多,可能還不知道如何在proc 下建立一個file 呢?其實比較簡單, 核心的function就是:
static inline struct proc_dir_entry *proc_create(
const char *name, umode_t mode, struct proc_dir_entry *parent,
const struct file_operations *proc_fops);
示例:
如果傳回非空,則表示file 建立成功,當然在建立的時候需要制定檔案名(name), 操作權限(mode),parent可以填NULL,proc_fops就是上文提到的file_operations.
proc_create 一般是放在init函數裡面,init 函數在linux kernel 裡面有兩種方法:
- 提供一個init 函數,由相關module init 的時候調用;
提供module init / module exit 函數入口,由kernel 加載或者手動inmod
moudle_init(void )/module_exit(void )