使用深度优先搜索遍历任务子级树的内核模块 [英] Kernel module that iterates over the tree of children of a task using depth first search

查看:36
本文介绍了使用深度优先搜索遍历任务子级树的内核模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道如何创建内核并线性迭代进程,只需包含linux/sched.h并使用以下代码:

struct task_struct *task;

for_each_process(task)
{
   printk("Name: %s PID: [%d]
", task->comm, task->pid);
}
如何使用深度优先搜索打印这些任务?我希望我的输出类似于ps -eLf的输出。

提供了以下代码补丁以供参考:

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。

哪些字段用于状态和父PID?

推荐答案

这有点老了,但我无意中发现了它,因为它似乎是Operating System Concepts 9th Edition第3章中找到的编程项目之一,所以其他人可能还会来查看。

您开始的代码直接从本书开始,但它是一个很好的起点。您只需要实现DFS。以下是实现它的代码,它应该非常不言自明:

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆