#include<linux/sched.h>
#include<linux/pid.h>
#include<linux/slab.h>
#include<linux/module.h>
#include<linux/kernel.h>
static int pidnum = 1;//将之前后台运行的进程的pid通过此模块参数传给模块
module_param(pidnum,int,0644);
static int hello_init(void)
{
struct task_struct *p = NULL;
struct mm_struct *tmp;
struct pid *kpid = find_get_pid((int)pidnum);//用于将pidnum转换为kpid提供给pid_task
tmp = kmalloc(sizeof(*tmp),GFP_KERNEL);
if(tmp == NULL){
return -1;
}
printk(KERN_ALERT"pidnum = %d\n",pidnum);
p = pid_task(kpid,PIDTYPE_PID);//pid_task返回进程描述符,如果失败就按下面释放掉资源
if(p == NULL){
kfree(tmp);
printk(KERN_ALERT"find faild\n");
return -1;
}
if(p->mm == NULL){
kfree(tmp);
printk(KERN_ALERT"mm = NULL wrong\n");
}
else{
tmp->start_code = p->mm->start_code;
tmp->end_code = p->mm->end_code;
}
printk(KERN_ALERT"start_code : %lu, end_code :%lu",tmp->start_code,tmp->end_code);
printk(KERN_ALERT"pid = %u\n",p->pid);
kfree(tmp);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT"I free the malloc memory");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Qiao");
1.按如上编写函数之后,还需编写Makefile文件用于编译,我的文件命名为了hello.c,下面模块名也就叫hello.ko;
2.make 编译生成.ko文件;
3.depmod `pwd`/hello.ko,让modprobe 可以找到我们生产的模块,如果没有此步直接运行下一步将提示找不到模块
4.modprobe hello pidnum=(自己的进程号)
5.dmesg 可查看结果
6.modprobe -r hello ,卸载模块