数据不会写入/ proc文件

时间:2015-12-03 05:15:07

标签: c linux-kernel operating-system kernel

我编写了一个创建/ proc文件的内核模块。我还写了一个写入文件的用户空间代码,然后使用" copy_from_user"将该写入的数据提取到我的模块中。方法并在内核日志中打印。

数据在日志上成功写入,但是当我在编辑器中打开proc文件时,它就是空白。

任何人都可以解释为什么会这样吗?

用户空间代码是

#include<fcntl.h>

main()
{
    int fd=open("/proc/MY_PROC_FILE", O_RDWR);
    write(fd, "linux is awesome", 16);
    return 0;
}

模块

int open_callback(struct inode *p, struct file *q)
{
    printk(KERN_ALERT "open callback\n");
    return 0;
}

ssize_t write_callback(struct file *p, const char __user *buffer, size_t len, loff_t *s)
{
    printk(KERN_ALERT "write callback\n");
    char msg[256];
    copy_from_user(msg, buffer, len);
    printk("%s\n", msg);
    return 0;
}

static struct proc_dir_entry *my_proc_entry;

static struct file_operations fs={
    .open=open_callback,
    .read=read_callback,
    .write=write_callback,
    .release=release_callback
};

static int start(void)
{
    printk(KERN_ALERT "proc module registered\n");
    my_proc_entry=proc_create(file_name, 0, NULL, &fs);
    if(my_proc_entry==NULL)
    {
            printk(KERN_ALERT "os error\n");
            return -ENOMEM;
    }
    return 0;
}

static void stop(void)
{
    remove_proc_entry(file_name, NULL);
    printk(KERN_ALERT "proc module unregistered\n");
}

module_init(start);
module_exit(stop);
MODULE_LICENSE("GPL");

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:1)

您没有实施read_callback()

当你读取proc文件然后将调用read_callback()时。在这里,您需要编写代码以回写(使用copy_to_user())之前在write_callback()回调中编写的内容。

首先,您需要将用户在write_callback()中写入的内容存储在内核空间的某些全局内存中,然后才能将其写回read_callback()

这是您想要做的最好的例子。 http://www.makelinux.net/books/lkmpg/x810

相关问题