在根目录下创建一个文件夹,命名随意,这里我创建了一个名为“mymod”的文件夹:

编写Linux内核模块

在mymod文件夹下创建文件夹“hellomod”:

编写Linux内核模块

hellomod文件夹下有两个文件:

编写Linux内核模块

hello.c是我们编写的一个简单的内核模块:

编写Linux内核模块

可以看到这个内核模块真的非常简单,只包含了内核模块的加载函数、卸载函数。

Makefile用于编译内核:

编写Linux内核模块

准备好这两个文件后,打开一个终端,进到hellomod文件目录下:

编写Linux内核模块

执行Makefile编译内核:

编写Linux内核模块

加载内核:输入insmod hello.ko注意后缀!

输入lsmod查看加载进内核的模块:

编写Linux内核模块

输入rmmod hello 卸载模块:

输入dmesg查看内核打印出的信息:

编写Linux内核模块

回头看我们编写的内核模块:

编写Linux内核模块

内核加载的时候执行函数module_init(),函数module_init()执行函数hello_init,输出“Hello,world”

内核卸载的时候执行函数module_exit(),函数module_exit()执行函数hello_exit,输出“Goodbye,world”

hello.c代码:

/*                                                     
 * $Id: hello.c,v 1.5 2004/10/26 03:32:21 corbet Exp $ 
 */
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
        printk(KERN_ALERT "Hello, world\n");
        return 0;
}

static void hello_exit(void)
{
        printk(KERN_ALERT "Goodbye, world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile:                                     TAB TAB TAB 重要的事情说三遍

ifeq ($(KERNELRELEASE),)

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

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

modules_install:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
clean:
	rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions Module* modules*

.PHONY: modules modules_install clean
else
	obj-m :=hello.o
endif

 

相关文章: