[英]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_operations
的write
成員(在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 使用它自己的數據段作為“用戶”數據段。
首先,不要忽略警告:您的%d
對my_fd
。
然后,我認為通常從 kernel 進行文件 I/O 不是一個好主意,除非在“特殊”情況下。
我已經嘗試過 O_CREAT 並且一切都很好,除非文件已經存在。 其他一切(特別是O_WRONLY | O_APPEND
)都沒有給我機會。
我相信,為了在 kernel 中“作為”用戶空間中的文件 I/O 需要了解更多內容,這可能有點棘手(或“危險”)。
但是請嘗試查看acct.c代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.