首页 > 解决方案 > 内核模块:读取现有的 proc 文件 (proc_create)

问题描述

我是 Linux 内核的绝对新手。如果此问题已得到答复,我们深表歉意。我花了很多时间无法解决它,因此决定询问(也阅读 Linux 设备驱动程序书)。我的问题陈述:我想在我的内核模块(更多)中读取一个 proc 文件(/proc/pid/maps)。proc_create 上有许多示例,它们创建一个文件然后对其进行写入/读取。我只想读取现有的 proc 文件。似乎所有以前的选项都已被弃用(read_proc、create_proc_read_entry 等)。我读到的一个选项是从 task_mmu.c 调用 proc_pid_maps_operations。这是在调用 /proc/pid/maps 时涉及的吗?这是正确的方法吗?或者我可以抽象它。

来自各种教程的 proc_create 的代码片段在这里。当我将名称更改为现有文件时,insmod 失败。

        if (!proc_create( "testcpuinfo", // define ENTRY_NAME "hello_world"
                      0,             // permissions 0644 
                      NULL,          // proc directory
                      &fops))        // file_operations
    {
            printk("ERROR! proc_create\n");
            remove_proc_entry(ENTRY_NAME, NULL);
            return -ENOMEM;
    }

标签: linuxmodulekernelkernel-moduleproc

解决方案


我问这个问题是因为我想过滤掉 /proc/pid/maps。它有大量条目并影响我的工作负载的性能。感谢@0andriy 和@Tsyvarev 作为新手指导我。我已经包含了我必须过滤和生成修改后的地图的代码。我附上了代码片段,以防它帮助像我这样的新手生成他们的 /proc/pid/maps 版本。

  static int proc_show(struct seq_file *s, void *v) {
  struct task_struct *task;
  struct pid *pid_struct;
  struct mm_struct *mm;
  struct vm_area_struct *vma;
  unsigned long start, end;
  const char *region = NULL;

  // Look for task which PID was provided as parameter, falling back to current task if not found
  if(pid == 0) {
    printk(KERN_INFO "pages_activity: no pid argument provided, using current process instead\n");
    task = current;
  } else {
    pid_struct = find_get_pid(pid);
    if(pid_struct == NULL) {
      printk(KERN_INFO "pages_activity: process with pid %d not found, using current process instead\n", pid);
      task = current;
    } else {
      task = pid_task(pid_struct, PIDTYPE_PID);
    }
  }
  mm = task->mm;
  vma = mm->mmap;

推荐阅读