【问题标题】:How can I get a filename from a file descriptor inside a kernel module?如何从内核模块内的文件描述符中获取文件名?
【发布时间】:2012-01-05 05:03:26
【问题描述】:

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

【问题讨论】:

标签: c linux linux-kernel kernel-module


【解决方案1】:

不要调用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 *

【讨论】:

  • 不错。那行得通。谢谢!快速的问题。 path_getpath_put 调用的目的是什么(因为删除它们对我的程序没有太大影响)?另外,知道为什么sys_readlink 不工作吗?
  • @Siddhant:path_get()path_put() 调用是正确性所必需的,因为它们固定路径,以便在您尝试使用它时它不会消失(所有 @ 987654336@ 包含一对指针,指向 struct vfsmountstruct dentry)。
  • 还有,为什么一定要调用path_get获取路径结构的引用?
  • 与使用kmalloc 相比,从内存中分配单个页面是否有理由或好处?仅仅是因为您知道一个页面会满足路径数据的最坏情况要求吗?看来IS_ERRPTR_ERR 的混乱局面可以通过简单地使用后一种内存分配方法来避免。
  • @sherrellbc: 对,pagesize 是路径名可能大小的上限,所以使用kmalloc() 没有意义——d_path() 的返回值必须用@ 测试987654345@ 无论如何。在我们释放->file_lock 后,需要调用path_get() 以防止路径消失(因为此时文件可能被另一个线程并行关闭)。我们不想让->file_lock 保持超过必要的时间,因为它是一个自旋锁。
猜你喜欢
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多