Linux下hello.ko内核模块制作的全过程
所用的内核源码目录树下载地址: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
#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);
#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
在命令行进入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