Create a kernel module for Linux

A kernel module is a piece of code that extends the functionality of the Linux kernel, allowing you to add features without modifying the kernel source code.

Create the module

We will create a simple kernel module that prints messages when loaded and unloaded.

Create a file named hello_world.c with the following content:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>

// Function to execute when the module is loaded
static int __init hello_init(void)
{
        printk(KERN_INFO "Hello world! Module loaded!\n");
	    return 0;
}

// Function to execute when the module is unloaded
static void __exit hello_exit(void)
{
	    printk(KERN_INFO "Goodbye world! Module unloaded!\n");
}

// Specify module entry and exit points
module_init(hello_init);
module_exit(hello_exit);

Create the Makefile

Create a file named Makefile in the same directory as hello_world.c. This file specifies how to build and clean the kernel module:

obj-m += hello_world.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

Compile and load the kernel module

Run the following commands to compile the module and load it into the Linux kernel:

make
sudo insmod hello_world.ko

Verify the module is loaded

Use dmesg to check the kernel log for messages from your module:

dmesg | tail -n 3

You should see something like this:

[ 1129.698800] hello_world: loading out-of-tree module taints kernel.
[ 1129.698813] hello_world: module verification failed: signature and/or required key missing - tainting kernel
[ 1129.699946] Hello world! Module loaded!

Unload the kernel module

Remove the module from the Linux kernel:

sudo rmmod hello_world

Check the kernel log again to confirm the module was unloaded:

dmesg | tail -n 3

You should see something like this:

[ 1129.698813] hello_world: module verification failed: signature and/or required key missing - tainting kernel
[ 1129.699946] Hello world! Module loaded!
[ 1348.298657] Goodbye world! Module unloaded!

Congrats! You’ve just compiled and loaded your first kernel module!


Find this post helpful? Subscribe and get notified when I post something new!