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

标签 c linux linux-kernel kernel-module

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

最佳答案

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

广义上,给定一个 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);

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

关于c - 如何从内核模块内的文件描述符获取文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8250078/

相关文章:

linux - 如何在 shell 脚本中将单引号放在变量值内?

c - QEMU 向 qemu 二进制文件添加新参数

c - strtok 在调用函数中不起作用

c++ - gdb,为什么 "next"将每个源代码行显示两次?

linux - 轻量级Linux操作系统

c - 如何在 linux 用户空间应用程序中获得最精确的时钟?

linux - 只从 backports 编译一个特定的驱动程序?

c - 这两个声明有什么区别?

c - 将程序附加到进程 stdout/stderr

linux - 返回字符串比较结果 - bash