The init_module and cleanup_module of the fixed writing method of the Linux kernel module

1. Write the source code file helloworld.c

#include <linux/init.h> //The header file that all modules must include 
#include <linux/module.h> //Some macro definitions, such as KERN_INFO here

#define DRIVER_AUTHOR "[email protected]. cn"
#define DRIVER_DESC "A sample driver"  

int __init init_module(void)
{
    printk(KERN_INFO "------------Hello world----------\n"); //The previous macro indicates the level of printing  


    return 0; //Return non-0 indicates that the module failed to initialize and cannot be loaded
}

void __exit cleanup_module(void)
{
    printk(KERN_INFO "------------hello exit-----------\n"); 
}

//module's license 
MODULE_LICENSE("GPL");
//module's author
MODULE_AUTHOR(DRIVER_AUTHOR);
//module's description

MODULE_DESCRIPTION(DRIVER_DESC);

2. Write 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 := helloworld.o

endif

3. Compile the kernel module

Execute the make all or make command to generate the helloworld.ko module.

Fourth, install the kernel module

insmod helloworld.ko

5. View installed kernel modules

lsmod

xz@ubuntu2018:~/kernel/helloworld_2$ lsmod
Module                  Size  Used by

helloworld             16384  0

6. View the output information

dmesg

[150013.700804] ------------Hello world----------

7. Uninstall installed kernel modules

rmmod helloworld

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325883295&siteId=291194637
Recommended