What Is a Kernel Module?
A kernel module is a piece of code that can be dynamically loaded into or removed from the running kernel without rebooting. It allows us to:
- Extend kernel functionality (e.g., new drivers)
- Keep the kernel slim and modular
- Easily debug or test features
Kernel Module Lifecycle
All kernel modules must implement two functions:
static int __init my_module_init(void); // Called when module is loaded
static void __exit my_module_exit(void); // Called when module is removed
You must register these with macros:
module_init(my_module_init);
module_exit(my_module_exit);
Our First Kernel Module: Hello World
hello.c:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, Kernel World!\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, Kernel World!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A Simple Hello World Kernel Module");
Explanation:
KERN_INFO
: Log level__init
and__exit
: Compiler hints to free memory if the functions aren't needed after bootMODULE_*
macros add metadata (viewable withmodinfo
)
Creating the Makefile
Makefile
:
obj-m += hello.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
Explanation:
obj-m
: Specifies the kernel object to be built-C
: Tellsmake
to run in the kernel build directoryM=$(PWD)
: Points to your module's source directory
Building the Module
Step-by-Step:
Create the source files:
mkdir hello_module && cd hello_module nano hello.c nano Makefile
Build the module:
make
- You should now have a file:
hello.ko
Loading the Module
sudo insmod hello.ko
Check kernel logs:
dmesg | tail -n 10
Expected Output:
[ 1234.5678 ] Hello, Kernel World!
Unloading the Module
sudo rmmod hello
Check logs again:
dmesg | tail -n 10
Expected output:
[ 1234.9876 ] Goodbye, Kernel World!
Inspecting the Module
List all loaded modules:
lsmod
Show module info:
modinfo hello.ko
Expected metadata:
description: A Simple Hello World Kernel Module
author: Your Name
license: GPL
Leave a comment
Your email address will not be published. Required fields are marked *