linux内核模块编译

来源:互联网 发布:有道云笔记数据恢复 编辑:程序博客网 时间:2024/05/16 09:39

最近在学习linux内核模块,在初次编译时遇到了不少坑,下面是完整的内核模块编译流程。

写了一个简单的hello_world.c文件作为内核模块学习的第一步,代码如下:

#include <linux/init.h>#include <linux/module.h>static int __init hello_init(void){printk(KERN_INFO "Hello world,I'm in function %s!!!\n",__func__);return 0;}module_init(hello_init);  static void __exit hello_exit(void){printk(KERN_INFO "Bye Bye,I'm in function %s!!!\n",__func__);}module_exit(hello_exit);
同一目录下创建Makefile文件如下,内容如下:

KVERS = $(shell uname -r)obj-m += hello_world.o    build: kernel_moduleskernel_modules:    make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules    clean:    make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean
在初次编译时如果没有进行系统配置可能会出现无法找到linux/init.h或/lib/modules/$(KVERS)/build文件文件不存在等错误
解决方法如下:
(1)、控制台输入uname -r,得到系统版本号,本次测试使用的版本号是4.11.2;
(2)、根据版本号进入linux内核官网https://www.kernel.org/pub/linux/kernel/下载对应的linux内核源码;
(3)、将内核源码拷贝到/usr/src/目录并解压,然后cd进入linux目录,根据使用的平台进行make xxx_CONFIG;
(4)、进入内核模块源码目录进行编译,此时会报如下错误:
ERROR: Kernel configuration is invalid.
include/generated/autoconf.h or include/config/auto.conf are missing.
Run 'make oldconfig && make prepare' on kernel src to fix it.
cd进入linux源码目录,然后执行make prepare,完成后继续执行make scripts;
(5)、回到内核源码目录,输入make,即可完成内核模块编译。
使用命令insmod hello_world.ko加载刚刚编译完成的内核,使用dmesg | tail命令查看内核模块的信息输出如下:
[ 7471.722116] hello_world: loading out-of-tree module taints kernel.
[ 7471.723568] Hello world,I'm in function hello_init!!!
说明内核模块加载成功,使用lsmod 命令可以看到已经加载的所有内核:
Module                  Size  Used by
hello_world            16384  0
bnep                   20480  2
hci_uart               69632  1
btbcm                  16384  1 hci_uart
btqca                  16384  1 hci_uart
btintel                16384  1 hci_uart
bluetooth             335872  26 hci_uart,btintel,btqca,bnep,btbcm
ir_lirc_codec          16384  0
lirc_dev               20480  1 ir_lirc_codec
sunxi_cir              16384  0
rc_core                32768  4 ir_lirc_codec,lirc_dev,sunxi_cir
brcmfmac              204800  0
brcmutil               16384  1 brcmfmac
g_mass_storage         16384  0
usb_f_mass_storage     36864  1 g_mass_storage
libcomposite           45056  2 g_mass_storage,usb_f_mass_storage
使用rmmod hello_world命令可以移除内核模块,同时使用dmesg | tail查看内核输出如下:
[ 7530.123129] Bye Bye,I'm in function hello_exit!!!
至此完成内核模块的加载和移除过程。


原创粉丝点击