背景
在Linux内核中,已知一个进程的pid和其打开文件的文件描述符fd,如何获取该文件的绝对路径。
相关原理
1.通过进程pid获取进程描述符task_struct;
2.通过task_struct获取该进程打开文件结构files_struct,从而获取文件描述符表;
3.以fd为索引在文件描述符表中获取对应文件的结构体file;
4.通过file获取对应path结构,该结构封装当前文件对应的dentry和挂载点;
5.通过内核函数d_path()获取该文件的绝对路径;
实现方法
通过进程pid获取进程描述符demo:
1 | structtask_struct *get_proc(pid_t pid) |
3 | structpid *pid_struct = NULL; |
4 | structtask_struct *mytask = NULL; |
6 | pid_struct = find_get_pid(pid); |
9 | mytask = pid_task(pid_struct, PIDTYPE_PID); |
通过fd以及d_path()获取绝对路径demo:
1 | intget_path(structtask_struct *mytask, intfd) |
3 | structfile *myfile = NULL; |
4 | structfiles_struct *files = NULL; |
5 | charpath[100] = {'\0'}; |
10 | printk("files is null..\n"); |
13 | myfile = files->fdt->fd[fd]; |
15 | printk("myfile is null..\n"); |
18 | ppath = d_path(&(myfile->f_path), ppath, 100); |
20 | printk("path:%s\n", ppath); |