从Linux内核模块的文件描述符中获取文件名/路径? [英] Get file name/path from a file descriptor from a Linux kernel module?
问题描述
在Linux内核模块中,是否有一种方法可以从unsigned int fd
获取文件名/路径?
In a linux kernel module is there a way to get a file name/path from an unsigned int fd
?
I'm aware of this answer: How can I get a filename from a file descriptor inside a kernel module? but if I understand the code right, I need a struct files_struct
too.
请停止重复而不是重复的投票.我正在寻求一种从内核模块中以纯C语言获取文件名/路径的方法,而不是使用系统工具. 换句话说:在/procself/fd/上运行readlink并不是很好的答案.
Please stop voting as duplicated as it isn't. I'm asking for a way to get file's name/path in plain C from a kernel module, not using system tools. Said in another way: running readlink on /procself/fd/ is not a good answer.
内核的系统调用读取ssize_t read(int fd, void *buf, size_t count);
带有3个参数,其中之一是fd.显然,read
能够以某种方式从单个文件(而不是inode内的所有文件)读取.问题是如何.
Kernel's syscall read ssize_t read(int fd, void *buf, size_t count);
takes 3 arguments, one of them being a fd. It's obvious that somehow read
is able to read from a single file (instead of all files inside an inode). The question is how.
推荐答案
您所引用问题的答案中的代码是您需要执行的操作.是的,需要来自任务的struct files_struct
,因为文件描述符仅在files_struct
的上下文中才有意义(通常每个进程都有一个).文件描述符不是全局唯一的,只是单个打开文件表中的索引.
The code in the answer to the question that you reference is what you need to do. And yes, a struct files_struct
from a task is needed, because a file descriptor is only meaningful in the context of a files_struct
(usually, there is one of these per process). File descriptors aren't globally unique, just an index within an individual open file table.
如果您的代码在进程上下文中运行(例如,通过syscall调用),则可以将current->files
用于当前任务的files_struct
.这就是read()
的作用.
If your code is running in process-context (eg. invoked through a syscall) then you can use current->files
for the current task's files_struct
. This is what read()
does.
这篇关于从Linux内核模块的文件描述符中获取文件名/路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!