终于看到使用module的hello world了,哈哈哈
我使用的是Ubuntu10.04-64位的Desktop
建立源文件hello.c和Makefile:
hello.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk("Hello, world/n");
return 0;
}
static void hello_exit(void)
{
printk("Goodbye, cruel world/n");
}
module_init(hello_init);
module_exit(hello_exit);
Makefile:
obj-m := hello.o
源文件建好之后,用如下命令编译:
# make -C /usr/src/linux-headers-2.6.32-21-generic/ SUBDIRS=$PWD modules
编译的结果如下:
hello.c hello.ko hello.mod.c hello.mod.o hello.o Makefile modules.order Module.symvers
{
也可以这样来编译
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
然后运行 make 编译即可(不用带任何参数)
}
把hello.ko加载到内核中:
# insmod hello.ko
用lsmod或者查看文件/proc/modules可以发现"hello"已经被加载到内核中
把hello.ko从内核中移除:
# rmmod hello
再运行lsmod就会发现已经被移除了
查看/var/log/messages可以得到这个过程的打印信息,"Hello, world"出现啦!
# cat /var/log/messages
May 12 01:26:01 ubuntu rsyslogd: [origin software="rsyslogd" swVersion="4.2.0" x-pid="722" x-info="http://www.rsyslog.com"] rsyslogd was HUPed, type 'lightweight'.
May 12 01:42:51 ubuntu kernel: [ 2516.713810] Hello, world
May 12 01:42:59 ubuntu kernel: [ 2524.553781] Goodbye, cruel world