写一个Linux find_get_task_by_vpid函数的demo

以下是一个使用 find_get_task_by_vpid 函数的内核模块示例。该模块通过虚拟PID查找任务结构体并打印进程信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/pid.h>

static int target_vpid = 1;
module_param(target_vpid, int, 0644);

static int __init taskfinder_init(void)
{
struct task_struct *task;

printk(KERN_INFO "TaskFinder: 正在查找 vpid=%d\n", target_vpid);

rcu_read_lock();
task = find_get_task_by_vpid(target_vpid);
rcu_read_unlock();

if (!task) {
printk(KERN_ERR "TaskFinder: 找不到指定进程\n");
return -ESRCH;
}

printk(KERN_INFO "TaskFinder: 找到进程信息:\n"
"PID: %d\n"
"名称: %s\n"
"状态: %ld\n",
task->pid,
task->comm,
task->state);

put_task_struct(task);
return 0;
}

static void __exit taskfinder_exit(void)
{
printk(KERN_INFO "TaskFinder: 模块卸载\n");
}

module_init(taskfinder_init);
module_exit(taskfinder_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("通过vpid查找进程的演示模块");

配套Makefile

1
2
3
4
5
6
7
8
obj-m += taskfinder.o
KDIR ?= /lib/modules/$(shell uname -r)/build

all:
make -C $(KDIR) M=$(PWD) modules

clean:
make -C $(KDIR) M=$(PWD) clean

使用说明

  1. 保存代码为 taskfinder.c
  2. 编译模块:
    1
    make
  3. 插入模块(查看init进程):
    1
    sudo insmod taskfinder.ko target_vpid=1
  4. 查看输出:
    1
    dmesg | tail -n 8
  5. 移除模块:
    1
    sudo rmmod taskfinder

注意事项

  1. 需要root权限加载模块
  2. 不同内核版本API可能有差异(建议5.x+内核)
  3. 确保目标进程存在否则会报错
  4. 该模块仅用于演示,生产环境需要更完善的错误处理

输出示例:

1
2
3
4
5
[ 3487.123456] TaskFinder: 正在查找 vpid=1
[ 3487.123459] TaskFinder: 找到进程信息:
[ 3487.123461] PID: 1
[ 3487.123462] 名称: systemd
[ 3487.123463] 状态: 1