最简单的内核模块hello world

[root@localhost /home/ahao.mah/main]
#cat hello.c
// Defining __KERNEL__ and MODULE allows us to access kernel-level code not usually available to userspace programs.
#undef __KERNEL__
#define __KERNEL__ #undef MODULE
#define MODULE // Linux Kernel/LKM headers: module.h is needed by all modules and kernel.h is needed for KERN_INFO.
#include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros static int __init hello_init(void)
{
printk(KERN_INFO "Hello world!\n");
return 0; // Non-zero return means that the module couldn't be loaded.
} static void __exit hello_cleanup(void)
{
printk(KERN_INFO "Cleaning up module.\n");
} module_init(hello_init);
module_exit(hello_cleanup);
[root@localhost /home/ahao.mah/main]
#cat Makefile
obj-m := hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd) all:
$(MAKE) -C $(KDIR) M=$(PWD) modules clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
[root@localhost /home/ahao.mah/main]
#ll Makefile hello.c
-rw-r--r-- 1 root root 785 Dec 21 15:48 hello.c
-rwxr-xr-x 1 root root 170 Dec 21 15:51 Makefile
[root@localhost /home/ahao.mah/main]
#make
make -C /lib/modules/3.10.0-327.ali2000.alios7.x86_64/build M=/home/ahao.mah/main modules
make[1]: Entering directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
CC [M] /home/ahao.mah/main/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/ahao.mah/main/hello.mod.o
LD [M] /home/ahao.mah/main/hello.ko
make[1]: Leaving directory `/usr/src/kernels/3.10.0-327.ali2000.alios7.x86_64'
[root@localhost /home/ahao.mah/main]
#ls
hello.c hello.ko hello.mod.c hello.mod.o hello.o Makefile modules.order Module.symvers
[root@localhost /home/ahao.mah/main]
#lsmod | grep hello [root@localhost /home/ahao.mah/main]
#insmod hello.ko [root@localhost /home/ahao.mah/main]
#lsmod | grep hello
hello 12428 0
[root@localhost /home/ahao.mah/main]
#tail /var/log/messages
Dec 21 15:52:43 rt2m09617 kernel: hello: module license 'unspecified' taints kernel.
Dec 21 15:52:43 rt2m09617 kernel: Disabling lock debugging due to kernel taint
Dec 21 15:52:43 rt2m09617 kernel: hello: module verification failed: signature and/or required key missing - tainting kernel
Dec 21 15:52:43 rt2m09617 kernel: Hello world!
上一篇:iBatis基础知识


下一篇:2.4. 属性(Core Data 应用程序实践指南)