内核模块创建可读写/proc

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

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值