Linux kernel modules

1. Kernel module

A kernel module is a program with independent functions. It can be compiled by itself, but it cannot be run by itself, it must be linked to the kernel to run in kernel space as part of the kernel.

Second, write Makefile to compile the kernel module

obj -m + = source filename.o

all:

make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:

make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

3. After writing the Makefile, use make to compile. After compiling, a .ko file will appear. This is the kernel module, which needs to be loaded and run.

Fourth, load the kernel module to run

There are many ways to load kernel modules, such as : modprobe and insmod (install module), the former will analyze the dependencies of the module, and will go to the specified path to find the kernel module to load,

The latter requires specifying the absolute path of the kernel module to load and does not resolve module dependencies. Here use insmod to load the kernel module, use rmmod (remove module) to unload the kernel module.

[root@localhost kernel_module]# insmod hello.ko

Use dmes to view the quick Hello world of the kernel module

Uninstall the kernel module

[root@localhost kernel_module]# rmmod hello

dmesg view output Goodbye world

Five, the similarities and differences between kernel modules and application programming:

  • Kernel module programming cannot use standard libraries (such as malloc free, etc.) and some third-party libraries
  • There is no memory protection for kernel module programming. If the memory access is wrong, an oops error will occur
  • There is no main function in kernel module programming, only an initialization function and an exit function
  • Kernel module programming requires the use of header files and APIs provided by the kernel
  • The standard output of kernel module programming is to a file, not to the screen
  • The debug of kernel module programming cannot be debugged using gdb

Guess you like

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