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

时间:2011-11-23 22:40:37

标签: c linux linux-kernel kernel-module

我需要在我编写的一个小型Linux内核模块中从给定的文件描述符中获取文件的名称。我尝试了Getting Filename from file descriptor in C给出的解决方案,但出于某种原因,它打印出垃圾值(在解决方案中提到的readlink上使用/proc/self/fd/NNN)。我该怎么办?

1 个答案:

答案 0 :(得分:23)

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

从广义上讲,如果您感兴趣的任务中有int fdstruct 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);

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