helloworld of Linux kernel module development

The first step, write 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"  

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

    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_INFO "hello exit!\n");
}

module_init(hello_init);//Use a macro to specify the entry, and the loading function in the module will be called when loading the module  

module_exit(hello_exit);

//The license of the module 
MODULE_LICENSE("GPL");
//The author of the module
MODULE_AUTHOR(DRIVER_AUTHOR);
//The description of the module

MODULE_DESCRIPTION(DRIVER_DESC);

The second step, 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

The third step, compile

execute make all

The fourth step, execute insmod helloworld.ko

The fifth step, execute lsmod to view the installed kernel modules

The sixth part, view the output message, execute the command dmesg

 Hello world!

The seventh step, uninstall the module, execute rmmod helloworld, and view the output message, execute the command dmesg

hello exit!

The eighth step, clear the compilation, execute the make clean operation, and clear the files generated by the make all operation

Guess you like

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