我學習Linux內核,所以我嘗試寫一個簡單的模塊。Linux內核模塊奇怪的行爲
下面的代碼應該控制多少次read()
爲/proc/proc_test
被稱爲:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <asm/current.h>
static int __init init(void);
static void __exit stop(void);
static int proc_read(char *buffer, char **start, off_t offset, int size, int *eof, void *data);
static int counter = 0;
static int proc_read(char *buffer, char **start, off_t offset, int size, int *eof, void *data) {
if (size < 256) return -ENOMEM;
return sprintf(buffer, "counter = %d\n", counter++); <-- supposed to be incremented once
}
static int __init init() {
if (create_proc_read_entry("proc_test", 0, NULL, proc_read, NULL) == 0) {
printk(KERN_ERR "Can not creat entry\n");
return -ENOMEM;
}
printk("Entry created!\n");
return 0;
}
static void __exit stop() {
remove_proc_entry("proc_test", NULL);
printk("Entry removed!\n");
return;
}
module_init(init);
module_exit(stop);
MODULE_LICENSE("GPL");
我面對的是,當我使用cat
或tail
的/proc/proc_test/
讀取時,計數器加問題3,而不是由1
輸出:
cat /proc/proc_test
counter = 0
cat /proc/proc_test
counter = 3
cat /proc/proc_test
counter = 6
我做錯了什麼?
這似乎是一個解決方案。無論如何,我應該更加小心'read()'調用。 – Alex