1. Linux Kernel Module是什么

Linux Kernel Module是一段可以在运行时被加载到Linux Kernel中的代码,可以使用Kernel Functions。Linux Kernel Module的用途很广,最常见的例子就是Device Driver,也就是设备驱动程序。

如果没有Linux Kernel Module,每一行修改Kernel代码,每一个新增的Kernel功能特性,都需要重新编译Kernel,大大浪费了时间和效率。

2. kernel module编程

[root@localhost test]# ll
总用量 16
-rw-r--r--. 1 root root 728 4月  17 10:28 hello.c
-rw-r--r--. 1 root root 229 4月  17 10:24 Makefile
-rw-r--r--. 1 root root 190 4月  17 10:26 mymax.c
-rw-r--r--. 1 root root  70 4月  17 10:17 mymax.h

[root@localhost test]# cat hello.c 
#include <linux/init.h>		/* Needed for the module-macros */
#include <linux/module.h>	/* Needed by all modules */
#include <linux/configfs.h>     /* Needed for KERN_ALERT */

#include "mymax.h"

int a = 1; 
int b = 2; 
module_param(a, int, 0644); /* /sys/module/test/parameters/a  */
module_param(b, int, 0644); /* /sys/module/test/parameters/b  */
 
static int hello_init(void)
{
    printk("test, Hello world\n");
    printk("a + b = %d\n", a+b);
    mymax();
    return 0;
}
 
static void hello_exit(void)
{
    printk(KERN_ALERT "test, Good bye\n");
}
 
module_init(hello_init);
module_exit(hello_exit);  
MODULE_LICENSE("Dual BSD/GPL");  //should always exist or you’ll get a warning  
MODULE_AUTHOR("DONGFENG"); //optional  
MODULE_DESCRIPTION("STUDY_MODULE"); //optional 

EXPORT_SYMBOL(mymax); /* 别的module可以调用  */

[root@localhost test]# cat mymax.h
#include <linux/init.h>
#include <linux/module.h>
 
void mymax(void);

[root@localhost test]# cat mymax.c
//#include <linux/init.h>
//#include <linux/module.h>
 
#include "mymax.h"
//MODULE_LICENSE("Dual BSD/GPL");
 
void mymax(void)
{
    printk("test, enter max\n");
}

//EXPORT_SYMBOL(mymax);

[root@localhost test]# cat Makefile 
obj-m := test.o
#test-objs := hello.o mymax.o
test-objs := hello.o
test-objs += mymax.o
PWD := $(shell pwd)
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
	rm -rf *.o *.ko *~ *.mod.c *.order *.symvers

3 使用dmesg验证

[root@localhost test]# dmesg |tail -n 4
[170006.139126] test, Hello world
[170006.139131] a + b = 3
[170006.139133] test, enter max
[170980.892707] test, Good bye