我是 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(或随机 pid)
它不会停止执行并耗尽所有内核日志内存,最终卡住计算机。我习惯在恢复模式下重新启动它并删除爆炸的日志文件,但我不知道如何解决问题。我们将不胜感激所有帮助。
亲切的问候,
最佳答案
我通过初始化名为 childtask 的新 task_struct 解决了问题:
struct task_struct *childtask;
然后将其分配给list_for_each循环内的list_entry:
childtask = list_entry(list, struct task_struct, sibling);
这样任务和子任务是不同的指针。
关于C - Linux - 自定义内核模块来迭代进程的子进程会破坏内核日志和计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55431226/