First, the module file segmentation
When writing a program in user mode, a large program is divided into several files, and the program context is clear. Write the initialization function and the exit function separately in two files.
1. Write the initialization function in the start.c source file
#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. Write the exit function in the stop.c source file
#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");
}
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 += helloworld3.o
helloworld3-objs := start.o stop.o
endif
3. Compile the kernel module
Execute the make or make all command to generate the kernel module helloworld3.ko
Fourth, install the kernel module
sudo insmod helloworld3.ko
5. View installed kernel modules
lsmod
6. View the output information
dmesg
7. Uninstall installed kernel modules
sudo rmmod helloworld3
complete.