把自己编写的字符设备module添加到linux内核中编译的步骤如下:
<1> : 编写一个测试程序:
#include#include #include #include #include #include #define DEVICE_NAME "hellomodule"static struct file_operations dev_fops={.owner = THIS_MODULE};static struct miscdevice misc={.minor=MISC_DYNAMIC_MINOR,.name=DEVICE_NAME,.fops=&dev_fops};static int __init hello_module_init(){ int ret; printk("init hello module !\n"); ret=misc_register(&misc); return 0;}static void __exit hello_module_exit(){ printk("exit hello module !\n"); misc_deregister(&misc);}module_init(hello_module_init);module_exit(hello_module_exit);MODULE_AUTHOR("zhibao.liu");MODULE_DESCRIPTION("load in linux kernel demo .");MODULE_ALIAS("load in linux kernel demo .");MODULE_LICENSE("GPL");
程序中注册了一个device,编译装载后可以在/dev中看到hellomodule节点;
<2> 在编写相关的shell脚本:编译脚本:
#!/bin/bashmake -C /usr/src/linux-headers-3.8.0-29-generic M=/root/workspace/drivers/hellomodule
-C后面的是引用linux相关的头文件,放在什么样的linux系统中,就用那个linux的头文件,保证版本和系统一致,在后面装载到系统中才会运行OK;
装载模块脚本:
#!/bin/bashecho "-----------------------start hello module----------------------------"insmod hellomodule.kolsmod | grep hellomoduledmesg | grep hellomodulels /dev | grep hellomodulermmod hellomoduleecho "-----------------------exit hello module-----------------------------"echo "-----------------------check hellomodule-----------------------------"lsmod | grep hellomodulemodinfo hellomodule.ko
<3> : Makefile文件如下:
obj-m := hellomodule.o
经过上面所有的编写,所有的文件都已经编写完成.
<4> : 运行build.sh脚本,编译驱动程序,如下:
然后执行build_t.sh,装载卸载如下:
<5> : 如果没有任何问题,将上面的测试驱动拷贝到需要build的Linux内核根目录下的drivers/char目录下,拷贝后,需要修改该目录下两个文件,
Makefile文件,这个文件保证编译内核时,把刚才拷贝的hellomodule.c同时也编译进去,另外一个文件就是Kconfig,linux是个文件系统,各个文件
的组织需要很多配置文件组织,组成一个文件树,这样就可以一层一层的递归寻找的方式查找所有的文件,添加新的module需要被识别和添加,就需要
把文件的信息添加给配置文件Kconfig.
其实这里添加很简单,Makefile文件参照里面其他文件添加的方式添加就可以了:
obj-$(CONFIG_HELLO_MODULE) += hellomodule.o
Kconfig文件中插入:
config HELLO_MODULE bool "hello module test" default y
其中两个文件中保持HELLO_MODULE一致,这样关联添加字符设备和相关文件的联系.
<5> : 完成上面的步骤,回到内核根目录:
make menuconfig
如下:
<6> : 重新定制内核以后,重新build bzImage就有了新的linux内核了.
下面的文章介绍了添加module的基本知识和相关文件的关系:
http://blog.csdn.net/estate66/article/details/5886816
不过这篇文章中要注意: .config是make menuconfig后进行save后自动生成的,只需要选择就可以了,不需要人为添加一段code进去设置.