【问题标题】:Listing all processes information using c使用 c 列出所有进程信息
【发布时间】:2016-05-05 23:39:16
【问题描述】:

我想用 pid、ppid、comm 和 size 列出所有正在运行的进程。除了 ppid 和 size 之外,我有以下代码工作,所以如何做到这一点。

--代码--

#include <linux/slab.h>
#include <linux/types.h>
#include <linux/unistd.h>
#include "sched.h"
#include "sched1.h"


/* This function is called when the module t is loaded. */
 int process_init(void)   
 {
   printk(KERN_INFO "lOADING  MODULE \n");
   printk(KERN_INFO "PID \t PPID \t PNAME \t SIZE \n");

  struct task_struct *task;
  for_each_process(task)
  {
    printk(KERN_INFO "%d \t %d\t %s \t %d \n",   task->pid,task->ppid,task->comm,task->sz);
   }

        return 0;
  }

【问题讨论】:

  • execlp("ps","ps","-ef",(char *)NULL); 是否适合您的目的
  • 而不是哪一行?
  • @ishyfishy 他对printk 的使用意味着这是在内核中运行,而不是在用户进程中。他不能从内核调用execlp
  • 你能给我们你的内核版本吗?我在struct task_struct中找不到ppid和sz成员@
  • 这里也一样,所以问了如何获取父id和进程大小。

标签: c process linux-kernel


【解决方案1】:

task_struct中不直接编码父pid和vm总大小,需要调用task_ppid_nr获取父pid,使用task_struct-&gt;mm获取进程的vm大小。

尝试以下操作:

#include <linux/slab.h>
#include <linux/types.h>
#include <linux/unistd.h>
#include "sched.h"
#include "sched1.h"
int process_init(void)
{
    printk(KERN_INFO "lOADING  MODULE \n");
    printk(KERN_INFO "PID \t PPID \t PNAME \t SIZE \n");
    struct task_struct *task;
    struct mm_struct *mm;
    for_each_process(task)
    {
        mm = get_task_mm(task);
        printk(KERN_INFO "%d \t %d\t %s \t %d \n",
                task->pid, task_ppid_nr(task), task->comm, mm->total_vm);
    }

    return 0;
}

【讨论】:

  • 1.没有什么能阻止任务被释放 2. mm 可以为空 3. 如果不为空,则引用泄露 4. ->comm 要求锁定任务
  • @employeeofthemonth 很高兴你提出来,随时编辑答案。
猜你喜欢
  • 2021-01-29
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2021-03-16
  • 2019-06-05
  • 1970-01-01
相关资源
最近更新 更多