[英]Share memory from a Linux kernel module for a userspace process to access
[英]Opening a file from userspace from a Linux kernel module
我一直在關注以下教程,該教程用於從Linux內核模塊的用戶空間打開文件: http://www.howtoforge.com/reading-files-from-the-linux-kernel-space-module-driver-fedora-14
代碼如下:
#include <linux/module.h> // Needed by all modules
#include <linux/kernel.h> // Needed for KERN_INFO
#include <linux/fs.h> // Needed by filp
#include <asm/uaccess.h> // Needed by segment descriptors
int init_module(void)
{
// Create variables
struct file *f;
char buf[128];
mm_segment_t fs;
int i;
// Init the buffer with 0
for(i=0;i<128;i++)
buf[i] = 0;
// To see in /var/log/messages that the module is operating
printk(KERN_INFO "My module is loaded\n");
// I am using Fedora and for the test I have chosen following file
// Obviously it is much smaller than the 128 bytes, but hell with it =)
f = filp_open("/etc/fedora-release", O_RDONLY, 0);
if(f == NULL)
printk(KERN_ALERT "filp_open error!!.\n");
else{
// Get current segment descriptor
fs = get_fs();
// Set segment descriptor associated to kernel space
set_fs(get_ds());
// Read the file
f->f_op->read(f, buf, 128, &f->f_pos);
// Restore segment descriptor
set_fs(fs);
// See what we read from file
printk(KERN_INFO "buf:%s\n",buf);
}
filp_close(f,NULL);
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "My module is unloaded\n");
}
該代碼是從上面的鏈接復制粘貼的。 在運行3.11.10-200內核的Fedora 19的機器上,似乎未運行filp_open,為buf變量提供了空值。
有什么事嗎 我仍在學習Linux內核模塊開發的繩索。
您應該做的第一件事是檢查是否從filp_open
返回了任何錯誤(實際上,就現代內核而言,檢查NULL
可能是一個徹底的錯誤)。 正確的順序應為:
f = filp_open("/etc/fedora-release", O_RDONLY, 0);
if (IS_ERR(f)) {
// inspect the value of PTR_ERR(f), get the necessary clues
// negative values represent various errors
// as defined in asm-generic/errno-base.h
}
只有這樣,您才能繼續診斷讀取。
977 struct file *filp_open(const char *filename, int flags, umode_t mode)
978 {
979 struct filename *name = getname_kernel(filename);
980 struct file *file = ERR_CAST(name);
981
982 if (!IS_ERR(name)) {
983 file = file_open_name(name, flags, mode);
984 putname(name);
985 }
986 return file;
987 }
錯誤可能在於您如何放置參數,flags參數位於模式參數位置,反之亦然,模式位於falgs位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.