您的位置:首页 > 其它

内核第一个程序之Hello World!

2014-11-30 15:54 323 查看
这个程序是《Linuxdevicedrivers》中的代码片段:

#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("DualBSD/GPL");

staticinthello_init(void)
{
printk(KERN_ALERT"Hello,world\n");
return0;
}

staticvoidhello_exit(void)
{
printk(KERN_ALERT"Goodbye,Cruelworld\n");
}

module_init(hello_init);
module_exit(hello_exit);

下面是makefile,建议去看一下makefile的基本语法,$(MAKE)-C$(KERNELDIR)SUBDIRS=$(PWD)modules这句就是说首先改变目录到-C选项指定的目录(即内核源代码目录),其中保存了内核的顶层makefile文件。SUBDIRS=选项让该makefile在构造modules目标返回之前到模块源代码目录。然后,modules目标指向obj-m变量设定的模块。

ifneq($(KERNELRELEASE),)
obj-m:=hello.o
else
KERNELDIR:=/lib/modules/$(shelluname-r)/build
PWD:=$(shellpwd)
all:
$(MAKE)-C$(KERNELDIR)SUBDIRS=$(PWD)modules
endif
clean:
rm-f*.o*.ko*.mod.c.hello*

好了,然后安逸的make一下:

make-C/lib/modules/3.13.0-35-generic/buildSUBDIRS=/home/zachery/kernel_programmingmodules make[1]:Enteringdirectory`/usr/src/linux-headers-3.13.0-35-generic' CC[M]/home/zachery/kernel_programming/hello.o Buildingmodules,stage2. MODPOST1modules CC/home/zachery/kernel_programming/hello.mod.o LD[M]/home/zachery/kernel_programming/hello.ko make[1]:Leavingdirectory`/usr/src/linux-headers-3.13.0-35-generic'
接下来可以看效果了,

装载模块:insmod./hello.ko

卸载模块:rmmodhello

terminal是看不到输出的,消息进入了其中一个系统日志文件中,我当前的Ubuntu14.04是/var/log/syslog(实际文件名子随Linux发布而变化).可以使用tail-f/var/log/syslog查看。

ps:printk中优先级只是一个字串,前缀于printk格式串之前.注意在KERN_ALERT后面是不需要逗号的!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: