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

#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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值