【Linux内核】【Linux驱动】一个最简单的hello驱动模块

1. 简单驱动hello代码

1.1 驱动代码详情

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

static int __init hello_init(void) {
        printk(KERN_INFO "enter hello\n");
        return 0;
}

static void __exit hello_exit(void) {
        printk(KERN_INFO "exit hello\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_AUTHOR("Neo Nengrong Qu");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple kernel module hello");
MODULE_ALIAS("hello module");

2. 简单Makefile

2.1 详细makefile如下

KVERS = $(shell uname -r)

obj-m += hello.o

build: kernel_moudles

kernel_moudles:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules

clean:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean

2.2 编译输出

$ make
make -C /lib/modules/5.13.0-21-generic/build M=/home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko modules
make[1]: Entering directory '/usr/src/linux-headers-5.13.0-21-generic'
  CC [M]  /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/hello.o
  MODPOST /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/Module.symvers
  LD [M]  /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/hello.ko
  BTF [M] /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/hello.ko
Skipping BTF generation for /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/hello.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-5.13.0-21-generic'

3. 简单加载驱动hello

注意, 在新版本Ubuntu系统中, 内核日志记录在 /var/log/kern.log 文件中; 典型日志如下:

$ tail /var/log/kern.log
Dec 29 00:51:44 neo-hw-matebookxpro kernel: [110342.201119] enter hello
Dec 29 00:56:47 neo-hw-matebookxpro kernel: [110645.115691] exit hello

3.1 加载模块 hello

  • 没有任何错误提示信息,则表示加载成功, 可以查看 /var/log/kern.log

sudo insmod hello.ko


3.2 查看模块详情

  • 查看模块详情
$ modinfo hello.ko
filename:       /home/neo/neo-practice/linux-kernel-study/ldddd-4th/ch04-hello-ko/hello.ko
alias:          hello module
description:    Simple kernel module hello
license:        GPL
author:         Neo Nengrong Qu
srcversion:     2323F2B7A724DE963E5DE6B
depends:        
retpoline:      Y
name:           hello
vermagic:       5.13.0-21-generic SMP mod_unload modversions


$ tree /sys/module/hello/
/sys/module/hello/
├── coresize
├── holders
├── initsize
├── initstate
├── notes
├── refcnt
├── sections
│   └── __mcount_loc
├── srcversion
├── taint
└── uevent

3 directories, 8 files

3.3 移除模块 hello

  • 没有任何错误提示信息,则表示卸载成功, 可以查看 /var/log/kern.log

sudo rmmod hello


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逸云沙鸥のIHave@Dream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值