Sid*_*ant 16 c linux kernel-module linux-kernel
我需要从我编写的一个小型Linux内核模块中获取给定文件描述符中的文件名.我尝试了在C中从文件描述符获取文件名时给出的解决方案,但由于某种原因,它打印出垃圾值(在解决方案中提到的使用readlink时/proc/self/fd/NNN).我该怎么做?
caf*_*caf 24
不要调用SYS_readlink- 使用与procfs读取其中一个链接时相同的方法.从in proc_pid_readlink()和proc_fd_link()in开始fs/proc/base.c.
从广义上讲,给定一个int fd和struct files_struct *files你感兴趣的任务(你已经参考过),你想做:
char *tmp;
char *pathname;
struct file *file;
struct path *path;
spin_lock(&files->file_lock);
file = fcheck_files(files, fd);
if (!file) {
spin_unlock(&files->file_lock);
return -ENOENT;
}
path = &file->f_path;
path_get(path);
spin_unlock(&files->file_lock);
tmp = (char *)__get_free_page(GFP_KERNEL);
if (!tmp) {
path_put(path);
return -ENOMEM;
}
pathname = d_path(path, tmp, PAGE_SIZE);
path_put(path);
if (IS_ERR(pathname)) {
free_page((unsigned long)tmp);
return PTR_ERR(pathname);
}
/* do something here with pathname */
free_page((unsigned long)tmp);
Run Code Online (Sandbox Code Playgroud)
如果您的代码在进程上下文中运行(例如,通过系统调用调用)并且文件描述符来自当前进程,那么您可以使用current->files当前任务struct files_struct *.