c - 如何从内核读取文件
问题描述
我想从包含一些参数的内核模块中读取文件
我使用了以下源代码
#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->read
是NULL
我的内核版本是 4.15,我的 ubuntu 是 16
我错过了什么?
为什么f->f_op->read
是NULL
?
如何在模块加载时从用户空间读取一些参数?我认为最好使用文件。如果是这样,如何在内核中读取文件?
解决方案
推荐阅读
- jquery - 如何在 div 上显示 div 然后在 10 秒后消失?
- c# - 带有 Xamarin 表单的 CollectionView 中的属性 ItemTemplate 的“LoadTemplate 不应为空”
- r - 如何用随机数字替换数据集中的特定值?
- python - 如何在我希望派生类定义的抽象基类(Python 3+)中创建类级别属性?
- debugging - 常规调试选项(VS2017):“使用托管兼容模式”和带有枚举的结构
- java - 尽管运行代码以显示菜单,Java 小程序仍显示白屏
- google-sheets - 如何从索引中的数组公式返回日期值:匹配公式(左/右函数)
- class - UML 类图:依赖于两个类的属性和方法
- javascript - 如何解码base64解码文件并保存为pdf文件
- python-3.x - 无法将 python 列表中的第二项(路由器命令)传递给网络设备