我一直在关注从http://www.howtoforge.com/reading-files-from-the-linux-kernel-space-module-driver-fedora-14
的Linux内核模块打开用户空间文件的教程代码如下:
#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内核模块开发的知识。
答案 0 :(得分:1)
您应该做的第一件事是检查是否从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
}
只有这样,您才能继续诊断阅读。
答案 1 :(得分:1)
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位置。