linux的module的“hello world”程序

終於看到使用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

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章