C 如何从内核读取文件

C 如何从内核读取文件,c,linux,kernel,C,Linux,Kernel,我想从内核模块中读取包含一些参数的文件 我使用了以下源代码 #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/version.h> #include <linux/fs.h> // Needed by filp #include <linux/rbtree.h> #include

我想从内核模块中读取包含一些参数的文件

我使用了以下源代码

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/fs.h>      // Needed by filp

#include <linux/rbtree.h>
#include <linux/time.h>
#include <linux/atomic.h>
#include <linux/proc_fs.h>
#include <linux/jiffies.h>

#include <net/net_namespace.h>
#include <net/netns/generic.h>

#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/inetdevice.h>
#include <linux/if_ether.h>



int init_module(void)
{
    // Create variables
    struct file *f;
    char buf[128];
    mm_segment_t fs;
    int i;
    unsigned long long offset = 0;
    // 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
    // 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/lsb-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;
//使用0初始化缓冲区
对于(i=0;如果操作->读取(f,buf,128,&f->操作->读取);
//还原段描述符
set_fs(fs);
//查看我们从文件中读取的内容
printk(内核信息“基本单位:%s\n”,基本单位);
}
filp_close(f,NULL);
返回0;
}
空洞清理_模块(空洞)
{
printk(KERN_INFO“我的模块已卸载”\n);
}
但是这个函数崩溃了。我调试它,发现
f->f_op->read
NULL

我的内核版本是4.15,ubuntu是16

我错过了什么

为什么
f->f_op->read
NULL


如何在加载模块时从用户空间读取一些参数?我认为最好使用文件。如果是这样,如何在内核中读取文件?

这是否回答了您的问题?也许这也有帮助:@dragosht是的,事实上我必须使用内核_read()对于我的内核版本。谢谢!请随意回答。我将向您推荐您应该在用户空间中读取该文件,并在需要时将模块参数传递给模块。对于更大的数据块,请查看固件加载如何为其他模块工作。这是否回答了您的问题?也许这也有帮助:@dragosht是的,事实上我必须使用kernel_read()用于我的内核版本。谢谢!请随意回答。我将更新您应该在用户空间中读取该文件,并在需要时将模块参数传递给模块。有关更大的数据块,请查看其他模块的固件加载工作方式。