zoukankan      html  css  js  c++  java
  • Linux内核模块程序加载方法

    Linux提供了一种动态加载内核的机制,这种机制称为模块(Module),模块具有一下特点:
    1、模块本身不被编译入内核映像,从而控制了内核的大小。
    2、模块一旦被加载,它就和内核中的其它部分完全一样。
    为了方便理解,下面从一个最简单的内核模块“Hello World” 开始。
    (我的环境是:Ubuntu9.10 , linux-source-2.6.31)

    1、在/home/china/test中编写hello.c文件
    如下:
    #include<linux/init.h>
    #include<linux/module.h>
    MODULE_LICENSE("Dual BSD/GPL");  //声明GPL版权

    static int hello_init(void)         //加载
    {
    printk(KERN_ALERT "Hello World enter ");
    return 0;

    }

    static void hello_exit(void)     //卸载
    {
    printk(KERN_ALERT "Hello World exit ");

    }

    module_init(hello_init);
    module_exit(hello_exit);
    写好后保存退出;
    2、同一目录下编写Makefile
    obj-m :=hello.o
    保存退出;

    3、使用如下命令编译hello模块
    make -C  /usr/src/linux-headers-2.6.31-21-generic  M=$(pwd)  modules
    (注:-C后为系统内核存放路径,M后为hello.c源文件路径,因为在test目录下,所以用$(pwd)代替,如果不做该目录下,则要写全源文件的路径)
    4、编译结果如下:

    make:进入目录'/usr/src/linux-headers-2.6.31-21-generic'
      CC [M]  /home/china/test/hello.o
      Building modules, stage 2.
      MODPOST 1 modules
      CC      /home/china/test/hello.mod.o
      LD [M]  /home/china/test/hello.ko
    make:离开目录“/usr/src/linux-headers-2.6.31-21-generic”

    5、在test目录下你会看到生成了如下文件

    hello.c   hello.mod.c  hello.o     modules.order
    hello.ko  hello.mod.o  Makefile  Module.markers  Module.symvers
    其中hello.ko就是模块目标文件,
    6、将hello.ko加载进内核
    在终端下输入如下命令: sudo insmod  ./hello.ko
    查看加载的内容:           sudo dmesg | tail -n 1 
    此时输出信息:              Hello World enter
    7、将hello.ko模块卸载
    在终端下输入如下命令: sudo rmmod hello
    查看卸载的内容:           sudo dmesg | tail -n 1 
    此时输出信息:              Hello World exit
    8、模块卸载以后,使用  lsmod | grep hello 命令查看模块列表,如果没有任何输出,表示hello模块已被成功卸载。

  • 相关阅读:
    react组件之间传值方式
    html url 传递锚点并添加参数
    Spring Boot 构建WAR包
    Spring Boot Actuator 的使用
    Spring boot的启动加载原理
    intellij idea resin容器部署web工程
    Mybatis Mapper之见解
    踩坑----数据库阻塞
    redis缓存与数据库的记录不一致造成的问题.(乐观锁)
    H5中popstate事件的诡异行为
  • 原文地址:https://www.cnblogs.com/i0ject/p/3656786.html
Copyright © 2011-2022 走看看