首页 > 解决方案 > 如何从内核读取文件

问题描述

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

我使用了以下源代码

#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");
}

但是这个函数崩溃了。我调试它,我发现那f->f_op->readNULL

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

我错过了什么?

为什么f->f_op->readNULL

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

标签: clinuxkernel

解决方案


推荐阅读