1、环境介绍
window 7 + VMware Workstation 9.0 + Ubuntu 12.04 LTS
注:没装什么其它工具,默认安装的Ubuntu 12.04。
2、参考资料
LDD3
http://lwn.net/Kernel/LDD3/
CHAPTER 2: Building and Running Modules
注:源代码直接从原书中复制即可。
3、创建源文件
创建了两个文件
1) home/ldd/hello_module/hello.c
2) home/ldd/hello_module/Makefile
hello.c中的源代码为:
- #include <linux/init.h>
- #include <linux/module.h>
- MODULE_LICENSE("Dual BSD/GPL");
- static int hello_init(void)
- {
- printk(KERN_ALERT "Hello, worldn");
- return 0;
- }
- static void hello_exit(void)
- {
- printk(KERN_ALERT "Goodbye, cruel worldn");
- }
- module_init(hello_init);
- module_exit(hello_exit);
Makefile中的源代码为:
- # If KERNELRELEASE is defined, we've
been invoked from the - # kernel build system and can use its language.
- ifneq ($(KERNELRELEASE),)
- obj-m := hello.o
- # Otherwise we were called directly from the command
- # line; invoke the kernel build system.
- else
- KERNELDIR ?= /lib/modules/$(shell
uname -r)/build - PWD := $(shell pwd)
- default:
- $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
- endif
4、编译ko文件
在home/ldd/hello_module/ 目录下,执行 make命令,生成hello.ko文件。
5、加载模块
输入命令 insmod hello.ko
卸载模块 rmmod hello.ko
查看已加载的模块 lsmod
在/var/log/syslog文件中有"Hello, world"和"Goodbye, cruel world"。
注:insmod命令需要su权限。
总结:
我一开始以为要有内核源代码才能编译模块,看了Makefile中的代码,感觉直接
编译就行。一试果然行!不需要再去手动建立任何源代码树,ubuntu中直接就能
编译通过!关于Makefile中的源代码解释,请参考ldd原书中的内容!
遗留:
如何让printk打印输出的信息直接在Terminal中显示,从而不需要再去查看
/var/lg/syslog这个文件。
2012年12月23日21:48:06:
对遗留的回复: dmesg | tail -5 可以显示syslog的最后5条记录,方便在Terminal中查看吧。