如何迭代PCB以在Linux内核模块中显示信息?

Rod*_*oCR 4 kernel pid module process

我想写一个小的Linux内核模块,它可以显示所有正在运行的进程的PID.我有以下代码:

/*
 * procInfo.c  My Kernel Module for process info
 */

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

/*
 * The init function, called when the module is loaded.
 * Returns zero if successfully loaded, nonzero otherwise.
 */
static int mod_init(void)
{
        printk(KERN_ALERT "ProcInfo sucessfully loaded.\n");
        return 0;
}

/*
 * The exit function, called when the module is removed.
 */
static void mod_exit(void)
{
        printk(KERN_ALERT "ProcInfo sucessfully unloaded.\n");
}

void getProcInfo()
{
        printk(KERN_INFO "The process is \"%s\" (pid %i)\n",
        current->comm, current->pid);
}

module_init(mod_init);
module_exit(mod_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Rodrigo");
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我知道我必须使用*struct task_struct*结构来获取PID和进程名称,但我使用的是当前的,我知道一些包含所有PCB的双链接循环列表的存在,所以主要问题是:我需要添加什么来迭代这个链接的lisk与p-next_task和p-prev_task所以getProcInfo有效?谢谢!

sar*_*old 6

以下宏include/linux/sched.h可能很有用:

#define next_task(p) \
    list_entry_rcu((p)->tasks.next, struct task_struct, tasks)

#define for_each_process(p) \
    for (p = &init_task ; (p = next_task(p)) != &init_task ; )
Run Code Online (Sandbox Code Playgroud)

您可能需要tasklist_lock在调用这些宏之前保留它们; 有几个如何锁定,迭代和解锁的例子mm/oom_kill.c.


Nod*_*ade 5

实际上,对于较新的内核(2.6.18和更新版本),列出任务的正确方法是持有rcu锁,因为任务列表现在是RCU列表.也tasklist_lock不再导出符号 - 这意味着当您编译可加载的内核模块时,此符号将不可见.

要使用的示例代码

struct task_struct *task;
rcu_read_lock();                                                    
for_each_process(task) {                                             
      task_lock(task);                                             

      /* do something with your task :) */

      task_unlock(task);                                           
}                                                                    
rcu_read_unlock();                       
Run Code Online (Sandbox Code Playgroud)

关于Linux内核源代码目录中RCU的文档也很有用,你会发现它 Documentation/RCU