C 从Linux内核模块从用户空间打开文件
我一直在学习从用户空间从Linux内核模块打开文件的教程 代码如下:C 从Linux内核模块从用户空间打开文件,c,linux,linux-kernel,kernel-module,C,Linux,Linux Kernel,Kernel Module,我一直在学习从用户空间从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 seg
#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");
}
#包括//所有模块所需
#包含//所需的内核信息
#包括//filp需要的
#包含//段描述符所需的
int init_模块(void)
{
//创建变量
结构文件*f;
char-buf[128];
mm_段_tfs;
int i;
//使用0初始化缓冲区
对于(i=0;如果操作->读取(f,buf,128,&f->操作->读取);
//还原段描述符
set_fs(fs);
//查看我们从文件中读取的内容
printk(内核信息“基本单位:%s\n”,基本单位);
}
filp_close(f,NULL);
返回0;
}
空洞清理_模块(空洞)
{
printk(KERN_INFO“我的模块已卸载”\n);
}
代码是从上面的链接复制粘贴的。在我的机器上,运行3.11.10-200内核的Fedora 19,似乎没有运行filp_open,为buf变量提供空值
有什么问题吗?我仍在学习Linux内核模块开发的诀窍。您应该做的第一件事是检查filp\u 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参数位于mode参数位置,反之亦然,mode位于falgs位置
来源:不要打开内核内部的文件。如果你需要从内核打开文件,99.99%的情况下,你是做错了。我这样做是为了证明概念。当我让它工作时,我计划使用块设备来实现它。我得到的错误代码是0,这对应于所有打开的东西都应该打开。也许吧结构有问题吗?