模块编写过程:
模块代码分为三大部分:
1.必要的头文件:
#include <linux/module.h>
2.模块规范与接口:
MODULE_LICENSE("Dual BSD/GPL");
module_init(init_hello_module);
module_exit(exit_hello_module);
3.模块初始化函数与结束函数:
int init_hello_module(void)
{
//函数内容
}
void exit_hello_module(void)
{
//函数内容
}
简单模块示例:
#include <linux/module.h>
int init_hello_module(void)
{
printk("***************Start***************\n");
printk("Hello World! Start of hello world module!\n");
return 0;
}
void exit_hello_module(void)
{
printk("***************End***************\n");
printk("Hello World! End of hello world module!\n");
return;
}
MODULE_LICENSE("Dual BSD/GPL");
module_init(init_hello_module);
module_exit(exit_hello_module);
编写好模块代码(如示例,命名为hello.c)后,我们需要将其编译生成相应的模块(hello.ko),并将其挂载。这个过程我们需要完成以下步骤:
1.首先需要 编写makefile文件:# To build modules outside of the kernel tree, we run "make"
# in the kernel source tree; the Makefile these then includes this
# Makefile once again.
# This conditional selects whether we are being included from the
# kernel Makefile or not.
# called from kernel build system: just declare what our modules are
obj-m := hello.o
CROSS_COMPILE =
CC = gcc
# Assume the source tree is where the running kernel was built
# You should set KERNELDIR in the environment if it's elsewhere
# KERNELDIR ?= /usr/src/linux-headers-$(shell uname -r)
KERNELDIR ?= /home/ccc/kernel/linux-$(shell uname -r)
# The current directory is passed to sub-makes as argument
PWD := $(shell pwd)
all: modules
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
rm -rf *.o *~ core .depend *.symvers .*.cmd *.ko *.mod.c .tmp_versions $(TARGET)
注意其中KERNELDIR ?= /home/ccc/kernel/linux-$(shelluname -r)的路径要更改为自己的内核路径。
2. 编译生成hello.ko。
make
3.
挂载该模块:
insmod hello.ko
4.
查看模块挂载情况:
lsmod |grep hello
或者dmesg,查看hello初始化输出信息。
dmesg
5.卸载该模块:
rmmod hello.ko
利用模块实现守护进程:
在科研工作中,我们经常需要周期性或触发性,监控并改变内核中一些内容。这里我们提供以内核模块,来实现这一功能。
回到内核初始化函数:int init_hello_module(void)
{
printk("***************Start***************\n");
printk("Hello World! Start of hello world module!\n");
test_task = kthread_create(threadfunction, NULL, "test_task");
if(IS_ERR(test_task)){
printk("Unable to start kernel thread.\n");
err = PTR_ERR(test_task);
test_task =NULL;
return err;
}
wake_up_process(test_task);
return 0;
}
我们可以创建一个进程,并使其完成我们想要做的任务,任务函数为threadfunction(这里递增打印hello):
int threadfunction(void *data){
int i = 0;
while(1){
set_current_state(TASK_INTERRUPTIBLE);//将当前的状态表示设置为休眠
if(kthread_should_stop()) break; //解释见“注意”
printk("Hello %d!\n",i++);
schedule_timeout(HZ); // 休眠,与set_current_state配合使用,需要计算,这里表示休眠一秒
}
return 0;
}
重新编译挂载模块,在dmesg中,我们可以周期性的获得输出信息。