【问题标题】:how to iterate over PCB's to show information in a Linux Kernel Module?如何遍历 PCB 以在 Linux 内核模块中显示信息?
【发布时间】:2011-07-30 10:26:16
【问题描述】:

我想编写一个小的 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");

如您所见,我知道我必须使用 *struct task_struct* 结构来获取 PID 和进程名称,但我使用的是 current,并且我知道存在一些 double包含所有 PCB 的链接循环列表,所以主要问题是: 我需要添加什么来使用 p-next_task 和 p-prev_task 迭代这个链接的 lisk 以便 getProcInfo 工作? 谢谢!

【问题讨论】:

    标签: process module kernel pid


    【解决方案1】:

    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 ; )
    

    您可能需要在调用这些宏之前按住tasklist_lockmm/oom_kill.c 中有几个如何锁定、迭代和解锁的示例。

    【讨论】:

    • 不是直接的答案,但它帮助我找到了答案!非常感谢!
    【解决方案2】:

    实际上,对于较新的内核(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();                       
    

    Linux 内核源代码目录中有关 RCU 的文档也很有帮助,您可以在 Documentation/RCU 中找到它

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 2015-07-08
      • 2013-03-19
      • 1970-01-01
      • 2018-06-18
      • 2011-11-24
      • 2011-02-10
      • 2012-04-11
      • 2013-12-17
      相关资源
      最近更新 更多