我已经看到很多关于从它的inode获取文件路径的问题,但几乎没有关于做反向的问题.我的内核模块需要这样做才能获得有关传递给请求主题的更多信息open(),例如文件标志或它是否是设备.从我能够从邮件列表,手册页和Linux源代码中搜集到的东西,我想出了这个小功能:
struct inode* get_inode_from_pathname(const char *pathname) {
struct path path;
kern_path(pathname, LOOKUP_FOLLOW, &path);
return path.dentry->d_inode;
}
Run Code Online (Sandbox Code Playgroud)
尝试在我的替换系统调用中使用它会使内核消息打印到控制台,但是:
struct inode *current_inode;
...
asmlinkage int custom_open(char const *__user file_name, int flags, int mode) {
current_inode = get_inode_from_pathname(file_name);
printk(KERN_INFO "intercepted: open(\"%s\", %X, %X)\n", file_name, flags, mode);
printk(KERN_INFO "i_mode of %s:%hu\n", file_name, current_inode->i_mode);
return real_open(file_name, flags, mode);
}
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?我几乎是肯定的,我的方式是错的.
小智 6
您可以使用kern_path内核API从路径字符串中获取inode信息.该函数依次调用do_path_lookup()执行路径查找操作的函数.您可以kern_path通过打印从函数获得的inode的inode编号(i_inoinode结构的字段)get_inode_from_pathname并将其与ls命令中的inode编号匹配来验证函数的结果(ls -i <path of the file>)
我制作了以下内核模块,并没有崩溃内核.我正在使用2.6.39内核.
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mount.h>
#include <linux/path.h>
#include <linux/namei.h>
#include <linux/fs.h>
#include <linux/namei.h>
char *path_name = "/home/shubham/test_prgs/temp.c";
int myinit(void)
{
struct inode *inode;
struct path path;
kern_path(path_name, LOOKUP_FOLLOW, &path);
inode = path.dentry->d_inode;
printk("Path name : %s, inode :%lu\n", path_name, inode->i_ino);
return 0;
}
void myexit(void)
{
return;
}
module_init(myinit);
module_exit(myexit);
//MODULE_AUTHOR("Shubham");
//MODULE_DESCRIPTION("Module to get inode from path");
MODULE_LICENSE("GPL");
MODULE_LICENSE("GPL v2");
Run Code Online (Sandbox Code Playgroud)
你能发送崩溃堆栈跟踪吗?