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

本文详细介绍了在Linux环境下创建并使用自定义内核模块hello.ko的全过程,包括安装Redflag6.0SP1系统及内核源码、编写模块代码、编译模块、安装和卸载模块等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

分类: UNIX   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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值