我已经看到很多关于从它的 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;
}
尝试在我的替换系统调用中使用它会使内核消息打印到控制台,但是:
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);
}
有一个更好的方法吗?我几乎可以肯定我的方式是错误的。
最佳答案
您可以使用 kern_path
内核 API 从路径字符串中获取 inode 信息。该函数依次调用 do_path_lookup()
执行路径查找操作的函数。您可以验证 kern_path
的结果通过打印从 i_ino
获得的 inode 的 inode 编号(inode 结构的 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");
你能发送崩溃堆栈跟踪吗?
关于linux-kernel - 在给定文件路径的情况下检索 inode 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869570/