下面介绍一个简单的module编程实现的小例子。
首先新建目录
$mkdir moduletest
$cd moduletest
模块代码编辑
$vim ModHello.c
在ModHello.c中加入如下内容:
#include
#include
#define CONFIG_MODVERSION
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include
#endif
static int __init modtest_init(void)
{
printk(KERN_EMERG "Hello, world - this is the kernel speaking\n");
return 0;
}
static void __exit modtest_exit(void)
{
printk(KERN_EMERG "Short is the life of a kernel module\n");
}
module_init(modtest_init);
module_exit(modtest_exit);
MODULE_LICENSE("GPL");
Makefile文件编辑
$vim Makefile
Makefile文件编辑内容入下:
# If KERNELRELEASE is defined, we've been invoked from the
# kernel build system and can use its language.
ifneq ($(KERNELRELEASE),)
obj-m := ModHello.o
# Otherwise we were called directly from the command
# line; invoke the kernel build system.
else
KERNELDIR ?= /lib/modules/`uname -r`/source
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
@echo "insmod ModHello.ko to install module"
@echo "rmmod ModHello.ko to uninstall module"
clean:
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions
endif
模块编译
$make
模块安装
$insmod ModHello.ko
模块卸载
$rmmod ModHello.ko
在虚拟终端中可能看不到模块安装和卸载时printk输出的内容,可以尝试组合按键ctrl+alt+F2切换到非图形界面进行模块的安装和卸载操作。
阅读(1902) | 评论(0) | 转发(0) |