嵌入式:内核驱动模块hello程序

本文详细介绍了一个简单的Linux模块的开发过程,包括源码编写、makefile配置、编译、安装及卸载模块等步骤,适用于初学者理解Linux内核模块的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的系统:

gyz@debian:~/der$ uname -a
Linux debian 4.19.0-0.bpo.2-amd64 #1 SMP Debian 4.19.16-1~bpo9+1 (2019-02-07) x86_64 GNU/Linux
gyz@debian:~/der$ lsb_release -a
No LSB modules are available.
Distributor ID:	Debian
Description:	Debian GNU/Linux 9.8 (stretch)
Release:	9.8
Codename:	stretch

 注意:

我这个是在linux系统上写的,所以用的是linux自己的内核源码,如果你是往开发板上移植,就用开发板上系统内核源码,并且用交叉编译器。

1,hello.c源码如下:

/*所有的模块带啊吗都要包含这两个头文件*/
#include <linux/module.h>
#include <linux/init.h>
/*代码所使用的许可证*/
MODULE_LICENSE("Dual BSD/GPL");
/*初始化代码*/
static int initialization_function(void)
{
	printk(KERN_ALERT "hello world!\n");
	return 0;
}
/*清除函数*/
static void cleanup_function(void)
{
	printk(KERN_ALERT "bye world!\n");
}

module_init(initialization_function);
module_exit(cleanup_function);

2,makefile文件内容

obj-m += hello.o
KERNEL_DIR += /lib/modules/$(shell uname -r)/build
PWD += $(shell pwd)
all:
	make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
#	make -C $(KERNEL_DIR) hello.c modules
clean:
	rm *.o *.ko *.mod.c

.PHONY:clean

-C指定内核源码文件目录,SUBDIRS指需要编译的.c文件的路径。 

3,编译

gyz@debian:~/der$ make
make -C /lib/modules/4.19.0-0.bpo.2-amd64/build SUBDIRS=/home/gyz/der /home/gyz/der modules
make[1]: Entering directory '/usr/src/linux-headers-4.19.0-0.bpo.2-amd64'
make[3]: Nothing to be done for '/home/gyz/der'.
  Building modules, stage 2.
  MODPOST 1 modules
make[1]: Leaving directory '/usr/src/linux-headers-4.19.0-0.bpo.2-amd64'

4,安装/显示/卸载模块

gyz@debian:~/der$ su -
密码:
root@debian:~# cd /home/gyz/der/
root@debian:/home/gyz/der# ls
hello.c   hello.mod.c  hello.o	Makefile       Module.symvers
hello.ko  hello.mod.o  m2	modules.order
root@debian:/home/gyz/der# insmod hello.ko 
insmod: ERROR: could not insert module hello.ko: File exists
root@debian:/home/gyz/der# rmmod hello.ko
root@debian:/home/gyz/der# insmod hello.ko
root@debian:/home/gyz/der# lsmod | grep "hello"
hello                  16384  0
root@debian:/home/gyz/der# rmmod hello.ko
root@debian:/home/gyz/der# lsmod | grep "hello"
root@debian:/home/gyz/der# dmesg | tail -6
[114720.199139] hello world!
[114739.031534] bye world!
[116357.767541] hello world!
[116889.978951] bye world!
[116900.055598] hello world!
[116925.801990] bye world!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值