嵌入式Linux简单内核模块的编程:
将以下hello.c和Makefile文件放在同一目录,然后make一下生成hello.ko文件
hello.c的内容:
#include "linux/module.h"
#include "linux/init.h"
static int __init
hellomodule_init(void) //模块初始化函数
{
printk("Hello_init! Are you ok ? oLHHo \n");
return
0;
}
static void __exit
hellomodule_exit(void) //模块退出函数
{
printk("Hello_exit! Oh_Yes!");
return
0;
}
module_init(hellomodule_init);
module_exit(hellomodule_exit);
MODULE_LICENSE("GPL");
一个简单的内核模块主要由4个部分组成:包含头文件、实现内核模块初始化函数和模块退出函数、使用module_init 和
module_exit
宏指定模块初始化函数和模块退出函数、声明模块license为"GPL",这4个部分是一个模块必需的,也就构成了内核模块的框架。
Makefile的内容:
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
KDIR
:=/home/olhho/opt/linux-2.6.30.9
#自己编译的内核的存放路径
all:
make -C $(KDIR) M=$(PWD) modules ARCH=arm
CROSS_COMPILE=arm-linux-
clean:
rm -f *.ko *.o *.mod.o *.mod.c *.symvers modul*
endif
obj-m:为内核顶层目录Makefile文件中使用的变量,表示要编译成模块的目标文件。Obj-m =
hello.o,表示将该目录下的hello.c模块源码文件编译成模块。
KDIR:内核目录,即用来编译模块的内核源码所以在目录。
ARCH=arm CROSS_COMPILE=arm-linux-:为arm配置交叉编译器
make出现以下错误:
root@olhho:/home/olhho/kernel_module#
make
make -C /home/olhho/opt/linux-2.6.30.9 M=/home/olhho/kernel_module
modules ARCH=arm CROSS_COMPILE=arm-linux-
make[1]: Entering directory `/home/olhho/opt/linux-2.6.30.9'
ERROR: Kernel
configuration is invalid.
include/linux/autoconf.h or include/config/auto.conf are
missing.
Run 'make oldconfig && make prepare' on kernel src to fix
it.
WARNING: Symbol version dump
/home/olhho/opt/linux-2.6.30.9/Module.symvers
is missing; modules will have no dependencies and modversions.
Building modules, stage 2.
/home/olhho/opt/linux-2.6.30.9/scripts/Makefile.modpost:43:
include/config/auto.conf: No such file or directory
make[2]: *** No rule to make target
`include/config/auto.conf'. Stop.
make[1]: *** [modules] Error 2
make[1]: Leaving directory `/home/olhho/opt/linux-2.6.30.9'
make: *** [all] Error 2
出现以上错误原因:自己太懒了,之前编译过的内核被移除了,新的内核没配置编译,果断重新配置编译,
然后,make生成hello.ko文件,再按照以下操作即可。
一.打开串口工具DNW:
1.移植内核 zImage
2.根文件系统 root_olhho.img
二.打开SecureCRT终端:
1.连接到板子,让板子跑起来
2.选择 Transfer-->Zmodem
Upload List...,然后选择 添加-->开始上传
3.加载模块命令:insmod(必须在当前目录下使用),例:
insmod hello.ko
使用lsmod(该命令可以不在当前目录使用),可以查看当前加载到内核的模块
删除模块命令:rmmod(该命令可以不在当前目录使用),删除不需要使用的内核模块
4.dmesg显示开机信息,查看printK信息
printk不显示在超级终端上,保存在/var/log/messages。
可以通过dmesg命令查看,如果只想显示最后几行,可以用
dmesg | tail - 8