您的位置:首页 > 运维架构 > Linux

Linux下hello.ko内核模块制作的全过程

2012-12-02 21:45 711 查看


Linux下hello.ko内核模块制作的全过程

分类: UNIX2011-08-06
14:22 656人阅读 评论(2) 收藏 举报

Linux下hello.ko内核模块制作的全过程

1. linux系统用的是Redflag 6.0 SP1 下载地址:ftp://ftp.redflag-linux.com/pub/redflag/dt6sp1/SP1/redflag-6-sp1.iso, 系统安装很容易,安提示做就好。

所用的内核源码目录树下载地址:ftp://ftp.redflag-linux.com/pub/redflag/dt6sp1/SP1/redflag-6-tool-sp1-src1.iso,将此iso文件挂载到/mnt下,安装其中的内核rpm包。

挂载方法:mount -t iso9660 redflag-6-tool-sp1-src1.iso /mnt/ -o loop

内核目录树安装方法:cd /mnt/RedFlag/SRMPS/

                    rpm -i kernel-2.6.23.1-4.src.rpm

3. 编写hello模块代码,源码如下:

#include <linux/init.h>

#include <linux/module.h>

MODULE_LICENSE("GPL");

static int hello_init(void)

{

  printk(KERN_ALERT "Hello, world\n");

  return 0;

}

static void hello_exit(void)

{

  printk(KERN_ALERT "Goodbye, cruel world\n");

}

module_init(hello_init);

module_exit(hello_exit);

4. 编写hello模块的Makefile文件,Makefile内容如下:

#Makefile 2.6

obj-m :=hello.o

KERNEL :=/usr/src/kernels/2.6.23.1-4-i686/

PWD :=$(shell pwd)

modules :

    $(MAKE) -C $(KERNEL) M=$(PWD) modules

.PHONEY:clean

clean :

    rm -f *.o *.ko

5. 编译模块

在命令行进入hello.c所在的文件夹下执行make命令即可完成hello模块的编译。用ls命令可以查看到hello.ko文件,此文件就是我们自定义的内核模块。

6. 安装hello模块
命令行下执行命令:insmod hello.ko即可。通过命令:cat /var/log/messages 

可以看到下面这样的信息:“Aug  6 13:37:59 localhost kernel: Hello, world”,说明模块加载成功了。

7. 另外一种模块Makefile的编写方法

# If KERNELRELEASE is defined, we've been invoked from the

# kernel build system and can use its language.

ifneq ($(KERNELRELEASE),)

 obj-m := hello.o 

# Otherwise we were called directly from the command

# line; invoke the kernel build system.

else

 KERNELDIR ?= /lib/modules/$(shell uname -r)/build

 PWD := $(shell pwd) 

default:

    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

endif

7. 卸载hello模块
命令行下执行命令:rmmod hello.ko即可。通过命令:cat /var/log/messages.

可以看到下面这样的信息:“Aug  6 13:40:36 localhost kernel: Goodbye, cruel world”,说明模块卸载成功。

8. 查看模块信息
命令行下执行命令:modinfo hello

分享到: 

上一篇:尾递归实现阶乘C语言实现,复杂度为O(n)下一篇:linux下安装virtualbox的一般方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: