In this lesson, you will learn the essential anatomy of a Linux kernel module and how to define its entry and exit points.
The Kernel Module Structure
Unlike a standard C program that starts execution at main(), a Linux kernel module is an object file that the kernel dynamically links into its own address space at runtime. Because it runs in kernel space (Ring 0), it lacks access to standard C library functions (like printf), relying instead on kernel-provided alternatives like printk.
To integrate your code, you must define two specific functions: one that runs when the module is inserted into the kernel, and one that runs when it is removed.
Defining Entry and Exit Points
We use specific macros to register these functions so the kernel knows how to manage our code's lifecycle. Here is a minimal implementation:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
static int __init my_module_init(void) {
printk(KERN_INFO "Hello, Kernel World!\n");
return 0; // Return 0 to indicate successful loading
}
static void __exit my_module_exit(void) {
printk(KERN_INFO "Goodbye, Kernel World!\n");
}
module_init(my_module_init);
module_exit(my_module_exit);
MODULE_LICENSE("GPL");
Understanding the Mechanics
module_initandmodule_exit: These macros register your functions. The kernel calls theinitfunction duringinsmod, and theexitfunction duringrmmod.__initand__exit: These are optimization tags. The__inittag tells the kernel that the function is only used during initialization, allowing the memory to be reclaimed after the module is loaded.printk: This is your primary diagnostic tool. Because the kernel is separate from the user-space terminal,printklogs messages to the kernel ring buffer, which you can view using thedmesgcommand.
By defining these boundaries, you transform a block of code into a functional piece of the operating system, allowing you to manipulate hardware and system resources at the most privileged level.
Key Takeaway: A minimal kernel module acts as a plugin for the Linux kernel, using registration macros to define specific startup and shutdown logic that integrates directly into the core operating system.