/*************************************************
* 使用seq_file接口實現可讀寫proc文件的例子
* 適用於3.10以後的內核
* Author: ZhangNa
* Date: 2015-5-17
* *************************************************/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
static char *str = NULL;
/*5,實現show函數
* 作用是將內核數據輸出到用戶空間
* 將在proc file輸出時被調用*/
static int my_proc_show(struct seq_file *m, void *v)
{
/*這裏不能使用printfk之類的函數
* 要使用seq_file輸出的一組特殊函數
* 詳見ldd3的91頁*/
// seq_printf(m, "current kernel time is %ld\n", jiffies);
seq_printf(m, "str is %s\n", str);
return 0;
}
/*3,實現open和write函數*/
static ssize_t my_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *f_pos)
{
char *tmp = kzalloc((count+1), GFP_KERNEL);
if(!tmp)
return -ENOMEM;
if(copy_from_user(tmp, buffer, count))
{
kfree(tmp);
return EFAULT;
}
kfree(str);
str = tmp;
return count;
}
static int my_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, my_proc_show, NULL);
}
/*2,填充proc_create函數中調用的flie_operations結構體
* 其中my開頭的函數爲自己實現的函數,
* seq和single開頭爲內核實現好的函數,直接填充上就行
* open爲必須填充函數
* 這裏詳見ldd3的93頁*/
static struct file_operations my_fops = {
.owner = THIS_MODULE,
.open = my_proc_open,
.release = single_release,
.read = seq_read,
.llseek = seq_lseek,
.write = my_proc_write,
};
static int __init my_init(void)
{
struct proc_dir_entry *file;
/*3.10以後內核的proc文件的新接口
* 需要關聯file_operations*/
/*1,首先要調用創建proc文件的函數,需要綁定flie_operations*/
file = proc_create("abc_proc", 0644, NULL, &my_fops);
if(!file)
return -ENOMEM;
return 0;
}
/*6,刪除proc文件*/
static void __exit my_exit(void)
{
remove_proc_entry("abc_proc", NULL);
kfree(str);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("ZhangNa");