【问题标题】:C - Linux - Custom kernel module to iterate over a process' children blows up kernel log and the computerC - Linux - 用于迭代进程的子进程的自定义内核模块会炸毁内核日志和计算机
【发布时间】:2019-03-30 21:42:28
【问题描述】:

我是 linux 内核模块的新手,我正在尝试在处理复杂的概念之前实现一些基本概念。我编写了一个代码,它接受一个模块参数(一个 int)并检查是否有一个带有该 pid 的进程。如果有,它将其子项作为列表并在打印子项的 ID 和描述时对其进行迭代。代码如下:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/moduleparam.h>
#include <linux/sched/signal.h>

MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Some guy");

int mypid = 0;

static int simple_init(void)
{

    struct task_struct *task;
    struct list_head *list;

    printk(KERN_ALERT "Loading Module\nThe process id: %d\n", mypid);


    for_each_process(task){
        printk(KERN_ALERT "PID/NAME: %d/%s\n", task->pid, task->comm);

        if(task->pid == mypid){

            printk(KERN_ALERT "The common pid found: %d/%s\n", task->pid, task->comm);


            list_for_each(list, &task->children){

            task = list_entry(list, struct task_struct, sibling);               
                //printk(KERN_INFO "Parent ID/NAME: %d/%s\n", task->parent->pid, task->parent->comm);               
                printk(KERN_ALERT "Child PID/NAME: %d/%s\n", task->pid, task->comm);
            }

    } 


    return 0;

}


static void simple_exit(void){

    printk(KERN_WARNING "Removing Module\n");

}

module_init(simple_init);
module_exit(simple_exit);
module_param(mypid, int, 0);

但是,当我运行此代码时

sudo insmod listtasks.ko mypid=1800(or a random pid)

它不会停止执行并吃掉所有内核日志内存,最终冻结计算机。我习惯于在恢复模式下重新启动它并删除崩溃的日志文件,但我看不出如何解决这个问题。我们将不胜感激所有帮助。

亲切的问候,

【问题讨论】:

  • 我认为你应该用read_lock(&amp;tasklist_lock);read_unlock(&amp;tasklist_lock);包装for_each_process

标签: c linux ubuntu linux-kernel kernel-module


【解决方案1】:

我通过初始化一个名为 childtask 的新 task_struct 解决了这个问题:

struct task_struct *childtask;

然后将其分配给 list_for_each 循环内的 list_entry:

childtask = list_entry(list, struct task_struct, sibling);  

因此 task 和 childtask 是不同的指针。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 2016-07-31
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    相关资源
    最近更新 更多