Linux 如何从内核模块内的文件描述符获取文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8250078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:32:06  来源:igfitidea点击:

How can I get a filename from a file descriptor inside a kernel module?

clinuxlinux-kernelkernel-module

提问by Siddhant

I need to get the name of a file from a given file descriptor, inside a small linux kernel module that I wrote. I tried the solution given at Getting Filename from file descriptor in C, but for some reason, it prints out garbage values (on using readlinkon /proc/self/fd/NNNas mentioned in the solution). How can I do it?

我需要从给定的文件描述符中获取文件名,在我编写的一个小的 linux 内核模块中。我尝试了从 C 中的文件描述符获取文件名中给出的解决方案,但由于某种原因,它打印出垃圾值(在解决方案中提到的使用readlinkon 时/proc/self/fd/NNN)。我该怎么做?

采纳答案by caf

Don't call SYS_readlink- use the same method that procfsdoes when one of those links is read. Start with the code in proc_pid_readlink()and proc_fd_link()in fs/proc/base.c.

不要调用SYS_readlink- 使用与procfs读取这些链接之一时相同的方法。从 inproc_pid_readlink()proc_fd_link()in 中的代码开始fs/proc/base.c

Broadly, given an int fdand a struct files_struct *filesfrom the task you're interested in (which you have taken a reference to), you want to do:

从广义上讲,给定您感兴趣的任务中的int fda 和 a 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);

If your code is running in process-context (eg. invoked through a syscall) and the file descriptor is from the current process, then you can use current->filesfor the current task's struct files_struct *.

如果您的代码在进程上下文中运行(例如,通过系统调用调用)并且文件描述符来自当前进程,那么您可以使用current->files当前任务的struct files_struct *.