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

文章目录

  • 1. 简单驱动hello代码
    • 1.1 驱动代码详情
  • 2. 简单Makefile
    • 2.1 详细makefile如下
    • 2.2 编译输出
  • 3. 简单加载驱动hello
    • 3.1 加载模块 hello
    • 3.2 查看模块详情
    • 3.3 移除模块 hello

1. 简单驱动hello代码

1.1 驱动代码详情

#include 
#include 

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


你可能感兴趣的:(#,Linux内核,linux,内核,驱动)