How to Create and Compile a Simple Module for the Linux Kernel

Introduction

Creating a Linux kernel module is a great way to learn how the Linux kernel works. This guide will show you how to create, compile, and load a simple "Hello World" kernel module step by step.

Preparation

Before we start, make sure you have the following:

Step 1: Writing the Module Code

Let's start by writing a simple kernel module that prints "Hello, World!" when loaded and "Goodbye, World!" when unloaded.

Create a file named hello.c and add the following code:

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

static int __init hello_init(void) {
    printk(KERN_INFO "Hello, World!\n");
    return 0;
}

static void __exit hello_exit(void) {
    printk(KERN_INFO "Goodbye, World!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Hello World module");
MODULE_VERSION("1.0");

Step 2: Creating the Makefile

Next, we need a Makefile to compile our module. Create a file named Makefile in the same directory as hello.c and add the following lines:

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: Compiling the Module

Now, we can compile the module using the make command. Open a terminal, navigate to the directory containing hello.c and Makefile, and run:

make

This will compile hello.c and generate a file named hello.ko, which is the kernel object file for our module.

Step 4: Loading and Unloading the Module

To load the module into the kernel, use the insmod command. You need superuser privileges for this, so prepend sudo:

sudo insmod hello.ko

To check that the module has been loaded, use the lsmod command:

lsmod | grep hello

You should see an entry for hello in the list of loaded modules. You can also check the kernel log messages to see the output of our module:

dmesg | tail

To unload the module, use the rmmod command:

sudo rmmod hello

Again, check the kernel log messages to see the "Goodbye, World!" message:

dmesg | tail

Conclusion

You have created, compiled, and loaded a simple Linux kernel module.