编写内核模块输出代码段的地址空间

来源:互联网 发布:微群控营销软件 编辑:程序博客网 时间:2024/06/18 15:26
#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 ,卸载模块

0 0
原创粉丝点击