Linux内核模块最简驱动

一、Makefile

在发行版下编译并运行内核模块是不需要交叉编译的,比如centos、ubuntu,无论当前是X86或者ARM架构,直接使用默认gcc即可,Makefile可有如下模板:

obj-m :=demo.o 
all:
        make -C /lib/modules/$(shell uname -r)/build SUBDIRS=$(PWD) modules
clean:
        make -C /lib/modules/$(shell uname -r)/build SUBDIRS=$(PWD) clean 

二、demo内核模块

内核模块必备的操作函数为:入口函数和出口函数,内核提供了固定的指定入口函数/出口函数的宏,即module_init/module_exit,只要实现这两个函数,即可完成了一个最简单的内核模块编程,有如下代码:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>

static int  __init demo_init(void)
{
        printk("demo init!\n");
        return 0;
}

static void __exit demo_exit(void)
{
        printk("demo exit!\n");
}

module_init(demo_init);
module_exit(demo_exit);

MODULE_LICENSE("GPL");

三、编译

[root@jingdomain demo]# make
make -C /lib/modules/4.18.0-348.2.1.el8_5.x86_64/build SUBDIRS=/root/temp/kernel_mod/demo modules
make[1]: Entering directory '/usr/src/kernels/4.18.0-348.2.1.el8_5.x86_64'
  CC [M]  /root/temp/kernel_mod/demo/demo.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /root/temp/kernel_mod/demo/demo.mod.o
  LD [M]  /root/temp/kernel_mod/demo/demo.ko
make[1]: Leaving directory '/usr/src/kernels/4.18.0-348.2.1.el8_5.x86_64'

通过make,最终执行生成demo.ko,这个ko模块就是我们将要运行的内核模块。

四、运行

通过insmod命令将编译得到的demo.ko,加载到内核系统中

[root@jingdomain demo]# insmod demo.ko
[root@jingdomain demo]# dmesg | tail -n 3
[469864.922449] demo: loading out-of-tree module taints kernel.
[469864.923609] demo: module verification failed: signature and/or required key missing - tainting kernel
[469864.925694] demo init!

当我们执行insmod的时候,内核会自动加载执行module_init传入的入口函数,demo模块仅仅是一条输出提示,仅仅会打印demo init!

如果我们想将这个内核模块卸载掉,我们可以用rmmod进行卸载

[root@jingdomain demo]# rmmod demo
[root@jingdomain demo]# dmesg | tail -n 1
[470029.429127] demo exit!
[root@jingdomain demo]# 

rmmod执行的过程中,会加载内核模块的module_exit传入的出口函数,以回收此模块的资源,本模块仅仅是打印了demo exit!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值