最简单的Linux内核模块例程

Posted on 2011-09-21 18:01  liuyanghejerry  阅读(753)  评论(0编辑  收藏  举报

一个Linux内核模块的Hello, World。有兴趣研究Linux内核的可以以此入门。

/*
* hello.c – 本例取自《Linux Kernel Development 3rd》,稍作修改
*/
//#include <linux/init.h> //早期的Linux内核源码存在这个头文件,2.6已经不存在了
#include <linux/module.h>
#include <linux/kernel.h>

static int hello_init(void)
{
printk(KERN_ALERT “I bear a charmed life.\n”);
return 0;
}

/*
* hello_exit – the exit function, called when the module is removed.
*/
static void hello_exit(void)
{
printk(KERN_ALERT “Out, out, brief candle!\n”);
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(“Your name here”);
MODULE_DESCRIPTION(“A Hello, World Module”);


相应的Makefile:

obj-m += hello.o

all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean


在终端载入编译好的模块:

insmod hello.ko

卸载模块:

rmmod hello.ko

代码中调用了printk,但是它并不会输出至终端的屏幕,而是会输出到/var/log/kern.log当中。


Copyright © 2024 liuyanghejerry
Powered by .NET 8.0 on Kubernetes