Selected topic
Kernel Modules
Prefer practical output? Use related tools below while reading.
====================================================
When writing a kernel module, it's essential to define init and exit functions to manage the initialization and cleanup processes. These functions are critical for loading, unloading, and maintaining the module.
### Init Function (__init)
The init function is responsible for initializing the module. It's called when the module is loaded into memory. The __init macro marks this function as non-critical; it won't be preserved in memory after the module is unloaded.
c
// init.cMODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, world!\n");
return 0;
}
module_init(hello_init);
In this example:
hello_init function with __init attribute.module_init macro is used to register the hello_init function as the initialization function for the module._exit)The _exit function, also known as the cleanup or exit function, is responsible for releasing any resources allocated by the module. It's called when the module is unloaded from memory.
c
// init.c (continued)static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, world!\n");
}
module_exit(hello_exit);
In this example:
_exit function with __exit attribute.module_exit macro is used to register the _exit function as the cleanup function for the module.To link the init and _exit functions to the kernel's initialization and exit routines, use the module_init and module_exit macros. These macros will take care of registering the functions with the correct hooks in the kernel.
c
// Makefileobj-m += init.o
To build and load the module:
makeinsmod init.ko