Selected topic

Init and Exit Functions

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.c

MODULE_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:

  • We define the hello_init function with __init attribute.
  • The module_init macro is used to register the hello_init function as the initialization function for the module.
### Exit Function (_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:

  • We define the _exit function with __exit attribute.
  • The module_exit macro is used to register the _exit function as the cleanup function for the module.
### Registration of Init and Exit Functions

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
// Makefile

obj-m += init.o

To build and load the module:

  1. Compile the kernel module using: make
  2. Load the module into memory using: insmod init.ko
  3. Check the kernel log for the output of both functions.
Note that this is a basic example, and actual kernel modules may require more complex initialization and cleanup processes depending on their functionality.