现在的位置: 首页 > 综合 > 正文

ubuntu hello module实验总结

2013年10月17日 ⁄ 综合 ⁄ 共 1322字 ⁄ 字号 评论关闭

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中的源代码为:
  1. #include <linux/init.h>
  2. #include <linux/module.h>

  3. MODULE_LICENSE("Dual BSD/GPL");

  4. static int hello_init(void)
  5. {
  6. printk(KERN_ALERT "Hello, worldn");
  7. return 0;
  8. }

  9. static void hello_exit(void)
  10. {
  11. printk(KERN_ALERT "Goodbye, cruel worldn");
  12. }

  13. module_init(hello_init);
  14. module_exit(hello_exit);

Makefile中的源代码为:

  1. If KERNELRELEASE is defined, we've
    been invoked from the
  2. # kernel build system and can use its language.
  3. ifneq ($(KERNELRELEASE),)
  4.     obj-:= hello.o
  5. # Otherwise we were called directly from the command
  6. # line; invoke the kernel build system.
  7. else
  8.     KERNELDIR ?= /lib/modules/$(shell
    uname -r)/build
  9.     PWD := $(shell pwd)
  10. default:
  11.     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
  12. 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中查看吧。

抱歉!评论已关闭.