Linux Device Driver - first Module

本文将指导您如何使用Linux内核源代码开发模块,包括模块的源代码编写、Makefile配置、模块编译、内核加载、输出信息打印及模块移除等步骤。

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

At first, you should have one linux kernal source code, and have opened "Enable Loadable module support" in Linux Kernal Configuration GUI by "$ sudo make menuconfig".


1. The source code of the module:

#include <linux/module.h> 
#include <linux/kernel.h> 
#include <linux/init.h>   
MODULE_LICENSE ("GPL");   
static int __init hello_2_init (void) 
{   
printk (KERN_INFO "Hello world\n");  
return 0;
}


static void __exit hello_2_exit (void)
{   
printk (KERN_INFO "Goodbye world\n"); 
}   
module_init (hello_2_init); 
module_exit (hello_2_exit);

2. Makefile

ifeq ($(KERNELRELEASE),) 

#KERNELDIR ?= /home/lht/kernel2.6/linux-2.6.14   
KERNELDIR ?= /lib/modules/$(shell uname -r)/build   
PWD := $(shell pwd)   
modules:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules   
modules_install:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install   
clean:
	rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions   
.PHONY: 
	modules modules_install clean  
else      
	obj-m := hello.o 
endi

 


3. Compile  "Hello" module
$ make
$ ls
hello.c  hello.c~  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers


4. Insert "Hello" module to kernal
$ sudo insmod hello   


5. Print module output message that was saved in the kernal message stack

$ sudo dmesg -c

[12104.762170] Hello world


6. Remove the "Hello" module

$ sudo rmmod hello

$ sudo dmesg -c 

[12143.629505] Goodbye world


Notes: 

mmzone.h:18:fatal error:gengerated/bounds.h:NO such file or directory

The mothod to solve this issue is we shoud go to  root dir  of current used kernal source code and execute:

$ make modules_prepare



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值