/*************************************************
* 使用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");