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

2023-12-19

我想编写一个 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,而且我知道存在一些包含所有 PCB 的双链循环列表,所以主要问题是: 我需要添加什么来使用 p-next_task 和 p-prev_task 迭代此链接链,以便 getProcInfo 起作用? 谢谢!


以下宏来自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_lock在调用这些宏之前;有关如何锁定、迭代和解锁的几个示例位于mm/oom_kill.c.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何迭代 PCB 以显示 Linux 内核模块中的信息? 的相关文章

随机推荐