使用深度优先树迭代所有任务的内核模块 [英] Kernel module that iterates over all tasks using depth first tree
问题描述
所以我知道如何创建内核并通过简单地包含 linux/sched.h
并使用以下代码来线性迭代进程:
So I know how to create a kernel and to iterate over the processes linearly by Simply including linux/sched.h
and using the following code:
struct task_struct *task;
for_each_process(task)
{
printk("Name: %s PID: [%d]
", task->comm, task->pid);
}
如何使用深度优先搜索打印这些任务?我希望我的输出类似于 ps -eLf
之一.
How can I print these tasks using a depth first search? I want my output to be similar to the one of ps -eLf
.
提供以下代码补丁供参考:
The following patch of code has been given for reference:
struct task_struct *task;
struct list_head *list;
list_for_each(list, &init_task->children) {
task = list_entry(list, struct task_struct, sibling);
/* task points to the next child in the list */
}
而且我知道 task->comm
返回名称,task->pid
返回该任务的 PID.
and I know that task->comm
returns the name and task->pid
returns the PID for that task.
返回状态和父pid用什么命令?
What commands are used to return the state and parent pid?
推荐答案
这有点老了,但我遇到了它,因为它似乎是在 操作系统概念第 9 版,所以其他人可能还会来看.
This is a bit old, but I came across it as it seems to be one of the programming projects found in chapter 3 of Operating System Concepts 9th Edition, so others may yet come looking.
您开始使用的代码直接来自书中,但它是一个很好的起点.您只需要实现 DFS.这是完成它的代码,它应该是不言自明的:
The code you started with is straight from the book, but it is a good starting point. You just need to implement the DFS. Here is the code that will accomplish it, it should be pretty self explanatory:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
/**
* Performs a DFS on a given task's children.
*
* @void
*/
void DFS(struct task_struct *task)
{
struct task_struct *child;
struct list_head *list;
printk("name: %s, pid: [%d], state: %li
", task->comm, task->pid, task->state);
list_for_each(list, &task->children) {
child = list_entry(list, struct task_struct, sibling);
DFS(child);
}
}
/**
* This function is called when the module is loaded.
*
* @return 0 upon success
*/
int task_lister_init(void)
{
printk(KERN_INFO "Loading Task Lister Module...
");
DFS(&init_task);
return 0;
}
/**
* This function is called when the module is removed.
*
* @void
*/
void task_lister_exit(void)
{
printk(KERN_INFO "Removing Task Lister Module...
");
}
// Macros for registering module entry and exit points.
module_init(task_lister_init);
module_exit(task_lister_exit);
这篇关于使用深度优先树迭代所有任务的内核模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!