繁体   English   中英

从 linux kernel 驱动程序写入文件失败

[英]File write from linux kernel driver failed

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>

static int __init hello_start(void)
{
    struct file* my_fd;

    my_fd = filp_open ("/tmp/foobar", O_WRONLY | O_APPEND, 0);
    if (IS_ERR (my_fd))
    {
    printk (KERN_ERR "Failed to open file. err: %d.\n", my_fd);
    }
    else
    {
    my_fd->f_op->write (my_fd, "some data", 10, &my_fd->f_pos);
    }

printk(KERN_INFO "Loading hello module...\n");
return 0;
}

static void __exit hello_end(void)
{
printk(KERN_INFO "hello_end.\n");
}

module_init(hello_start);
module_exit(hello_end);

上面的代码在写入文件时给出错误-14。 我在这里做错了什么?

这是dmesg output:

[19551.674999] Write returned: -14.
[19551.675004] Loading hello module...

struct file_operationswrite成员(在include/linux/fs.h )声明如下:

 ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);

请注意第二个参数上的__user标记,它告诉您它需要一个用户空间指针。 当你像从 kernel 那样调用它时,你传递的是一个内核空间指针; 因此您的 memory 故障。

@ShinTakezou 指向“acct.c”代码的链接是您想要查看的; 特别是,调用set_fs来欺骗 kernel 使用它自己的数据段作为“用户”数据段。

首先,不要忽略警告:您的%dmy_fd

然后,我认为通常从 kernel 进行文件 I/O 不是一个好主意,除非在“特殊”情况下。

我已经尝试过 O_CREAT 并且一切都很好,除非文件已经存在。 其他一切(特别是O_WRONLY | O_APPEND )都没有给我机会。

我相信,为了在 kernel 中“作为”用户空间中的文件 I/O 需要了解更多内容,这可能有点棘手(或“危险”)。

但是请尝试查看acct.c代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM