Chinaunix首页 | 论坛 | 博客
  • 博客访问: 49479
  • 博文数量: 7
  • 博客积分: 145
  • 博客等级: 民兵
  • 技术积分: 220
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-18 10:21
文章分类
文章存档

2013年(3)

2012年(4)

我的朋友

分类: LINUX

2012-11-25 18:17:09

下面介绍一个简单的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切换到非图形界面进行模块的安装和卸载操作。
阅读(1888) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~