Linux内核模块文件分割

一、模块文件分割

在用户态写程序的时候,会将一个大的程序分割成几个文件,程序脉络清晰。将初始化函数和退出函数分开在两个文件中编写。

1、在start.c源文件中编写初始化函数

#include <linux/kernel.h>   /* We're doing kernel work */
#include <linux/module.h>   /* Specifically a module */

int __init init_module(void)
{
    printk(KERN_INFO "Hello, world - this is the kernel speaking\n");

    return 0;

}

2、在stop.c源文件中编写退出函数

#include <linux/kernel.h>   /* We're doing kernel work */
#include <linux/module.h>   /* Specifically a module  */

void __exit cleanup_module()
{
    printk(KERN_INFO "Short is the life of a kernel module\n");

}

二、编写Makefile

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

all:                               
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules   
clean:                                             
        $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
else
    obj-m += helloworld3.o
    helloworld3-objs := start.o stop.o

endif

三、编译内核模块

执行make或make all命令,生成内核模块helloworld3.ko

四、安装内核模块

sudo insmod helloworld3.ko

五、查看已安装的内核模块

lsmod

六、查看输出信息

dmesg

七、卸载已安装的内核模块

sudo rmmod helloworld3

完毕。


猜你喜欢

转载自blog.csdn.net/xiezhi123456/article/details/80029004