IT技术博客大学习 共学习 共进步

Linux内核中通过文件描述符获取绝对路径

edsionte's TechBlog 2014-03-19 22:26:07 浏览 3,206 次

背景

在Linux内核中,已知一个进程的pid和其打开文件的文件描述符fd,如何获取该文件的绝对路径。

相关原理

1.通过进程pid获取进程描述符task_struct;

2.通过task_struct获取该进程打开文件结构files_struct,从而获取文件描述符表;

3.以fd为索引在文件描述符表中获取对应文件的结构体file;

4.通过file获取对应path结构,该结构封装当前文件对应的dentry和挂载点;

5.通过内核函数d_path()获取该文件的绝对路径;

实现方法

通过进程pid获取进程描述符demo:

1structtask_struct *get_proc(pid_t pid)
2{
3    structpid *pid_struct = NULL;
4    structtask_struct *mytask = NULL;
5
6    pid_struct = find_get_pid(pid);
7    if(!pid_struct)
8        returnNULL;
9    mytask = pid_task(pid_struct, PIDTYPE_PID);
10    returnmytask;
11}

通过fd以及d_path()获取绝对路径demo:

1intget_path(structtask_struct *mytask, intfd)
2{
3        structfile *myfile = NULL;
4        structfiles_struct *files = NULL;
5        charpath[100] = {'\0'};
6        char*ppath = path;
7
8        files = mytask->files;
9        if(!files) {
10                printk("files is null..\n");
11                return-1;
12        }
13        myfile = files->fdt->fd[fd];
14        if(!myfile) {
15                printk("myfile is null..\n");
16                return-1;
17        }
18        ppath = d_path(&(myfile->f_path), ppath, 100);
19
20        printk("path:%s\n", ppath);
21        return0;
22}

建议继续学习

  1. Linux 系统文件描述符继承带来的危害 (阅读 3,583)
  2. Zend Parameters Parser新增类型描述符介绍 (阅读 3,343)
  3. 使用Javascript获取页面所在目录的绝对路径 (阅读 2,745)
  4. Bash 中的 & 符号和文件描述符 (阅读 2,126)