How to Create a Linux Kernel Module
Prerequisites
Before you begin, make sure you have:
- A Linux system (with root access)
- Basic knowledge of C programming
- Kernel headers and development tools installed
To install the necessary tools on Ubuntu/Debian:
sudo apt-get updatesudo apt-get install gcc-12 build-essential linux-headers-$(uname -r)
Step 1: Create a Simple Kernel Module
Begin by creating a basic kernel module that can be loaded into and unloaded from the kernel. While it won’t perform any special functions, it serves as a “Hello World” example. Here’s how to do it:
Create a file named hello.c
and add the following code:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
// Initialization function (called when the module is loaded)
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, world!\n");
return 0; // Return 0 means success
}
// Exit function (called when the module is removed)
static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, world!\n");
}
// Register the functions
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Hello World Module");
MODULE_AUTHOR("Tecadmin.net");
Step 2: Create a Makefile
To compile the module, you’ll need a Makefile—a tool that aids in correctly building kernel modules.
Create a file named Makefile
in the same directory as your hello.c
file:
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
Step 3: Compile the Kernel Module
Now, compile the kernel module using the make
command.
- Open a terminal and navigate to the directory where your files are located.
-
Run the following command to compile the module:
make
If everything is set up correctly, this will generate a file named hello.ko
. This is your compiled kernel module.
Step 4: Test the Kernel Module
Now, it’s time to test your kernel module by loading it into the running kernel and checking its output.
-
Load the module: Use the
insmod
command to insert the module into the kernel.sudo insmod hello.ko
After running this, your kernel module should be loaded, and the
hello_init()
function will run. -
Check the output: Use the
dmesg
command to check the messages logged by the module.dmesg | tail
You should see the message
"Hello, world!"
in the output. -
Remove the module: Use the
rmmod
command to remove the module.sudo rmmod hello
This will unload the module and trigger the
hello_exit()
function. -
Check the output again: Run
dmesg | tail
again to see the"Goodbye, world!"
message in the output.
Step 5: Delete the Kernel Module
If you no longer need the kernel module, you can clean up the files using the make clean
command.
In the terminal, run:
make clean
This will remove the generated files, including the hello.ko
module, leaving only your source code (hello.c
and Makefile
).
https://tecadmin.net/how-to-create-a-kernel-module-for-linux/