- 論壇徽章:
- 0
|
hello wrold 模塊試驗(yàn)
參考http://linux.chinaunix.net/bbs/thread-1042600-1-2.html
步驟:
1. 在任意路徑下(最好擁有其權(quán)限)新建一目錄test,用于存放我們的代碼。
2. 在test目錄下新建源代碼文件hello.c,并敲入代碼
#include linux/init.h>
#include linux/module.h>
#include linux/kernel.h>
static int hello_init(void)
{
printk(KERN_ALERT "Hello, world!\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
3. 在test目錄下新建Makefile文件
obj-m := hello.o
KERNELDIR := /lib/modules/2.6.28-11-generic/build
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
注:
我這里KERNELDIR的值為 /lib/modules/2.6.28-11-generic/build[linux@ test]$ ll /lib/modules/2.6.28-11-generic/buildlrwxrwxrwx 1 root root 40 2009-12-05 08:47 /lib/modules/2.6.28-11-generic/build -> /usr/src/linux-headers-2.6.28-11-generic可以看到build文件實(shí)際上是軟鏈接到/usr/src/linux-headers-2.6.28-11-generic目錄的,該目錄下存放的是linux內(nèi)核頭文件,且仍保持內(nèi)核目錄結(jié)構(gòu)。
4. make 編譯
在目錄下生成數(shù)個(gè)文件
[linux@ test]$ lshello.c hello.mod.c hello.o Module.markers Module.symvershello.ko hello.mod.o Makefile modules.order
其中的hello.ko便是我們用來加載的模塊了
5. 加載模塊sudo insmod ./hello.ko
查看信息[linux@ test]$ dmesg | tail -n 1[22588.694732] Hello, world!
6. 卸載模塊[linux@ test]$ sudo rmmod hello[linux@ test]$ dmesg | tail -n 1[22665.554340] Goodbye, cruel world
小結(jié):注意要保證Makefile文件中引用的頭文件路徑KERNELDIR變量值正確。 這里只是將試驗(yàn)的過程記錄,至于對(duì)上面幾行代碼的解釋,google
本文來自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u3/93566/showart_2185885.html |
|