1.hello.c
#include
#include
MODULE_LICENSE("DualBSD/GPL");
MODULE_AUTHOR("MDAXIA");
static int __inithello_init(void)
{
printk(KERN_ALERT "Helloworld!n");
return 0;
}
static void __exithello_exit(void)
{
printk(KERN_ALERT "Goodbye,cruelworld!");
}
module_init(hello_init);
module_exit(hello_exit);
2.Makefile
ifeq ($(KERNELRELEASE),)
KDIR := /lib/modules/$(shell uname-r)/build
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KDIR) M=$(PWD)modules
modules_install:
$(MAKE) -C $(KDIR) M=$(PWD)modules_install
clean:
rm -rf *.o *.ko .depend *.mod.o*.mod.c Module.* modules.*
.PHONY:modules modules_installclean
else
obj-m :=hello.o
endif
3. 编译模块
#sudomake (调用第一个命令default)
这时,在hello.c 所在文件夹就会有 hello.ko,这个就是我们需要的内核模块啦
#sudo make clean
清理编译垃圾,hello.ko 也会清理掉。
4. 插入模块,让其工作。注意必须是root权限
#sudo insmod ./hello.ko
我们用dmesg 就可以看到 产生的内核信息啦,Hello world!
如果没有输出"hello from helloworld",因为如果你在字符终端而不是终端模拟器下运行的话,就会输出,因为在终端模拟器下时会把内核消息输出到日志文件/var/log/kern.log中。
#sudo rmmod ./hello
再用dmesg 可以看到 Bye world!
扩展阅读:
示例一 将开机信息发邮件
man dmesg 写道
The program helps users to print out their bootup messages.Instead of copying the messages by hand, the user need only:
dmesg > boot.messages
and mail the boot.messages file to whoever can debug their problem.
# dmesg >boot.messages
# ls -l boot.messages
-rw-r--r-- 1 root root 15838 12-09 12begin_of_the_skype_highlighting 15838 12-0912 免费 end_of_the_skype_highlighting:55boot.messages
# mail -s "Boot Log of Linux Server"public@web3q.net
#
通过管道查找
dmesg | grep world
dmesg | tail
dmesg -a
dmesg -c打印并清除