我需要从一个给定的文件描述符中获取一个文件的名称,在我写的一个小型Linux内核模块中。 我尝试了从C中的文件描述符获取文件名中给出的解决scheme,但由于某种原因,它打印出垃圾值(在解决scheme中提到的在/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);
如果你的代码运行在进程上下文中(例如,通过系统调用来调用),并且文件描述符来自当前进程,那么你可以使用当前任务的struct files_struct *
current->files
。