Skip to content

First Module

Linux kernel modules are compiled separately from the main kernel and loaded at runtime. A basic module must define an init function (called on module load) and an exit function (called on module removal). This section demonstrates creating a "Hello World" module with these functions and adding module parameters for runtime configuration.


Module Code Structure

Create a file hello.c with the following content:

#include <linux/module.h>   // Required for module macros
#include <linux/kernel.h>   // Required for printk()

// Module metadata
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Hello World module");

// Init function: Called when the module is loaded
int hello_init(void) {
    printk(KERN_INFO "Hello, World! Module loaded.\n");
    return 0; // Return 0 for success
}

// Exit function: Called when the module is removed
void hello_exit(void) {
    printk(KERN_INFO "Goodbye, World! Module removed.\n");
}
  • printk() sends messages to the kernel log. The KERN_INFO level ensures the message appears in /var/log/syslog or via dmesg.
  • MODULE_LICENSE() is required to avoid kernel restrictions; use "GPL" for open-source modules.

Adding Module Parameters

Extend the module to accept a parameter at load time. Modify hello.c:

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

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Hello World with parameters");

// Define a module parameter
char *greeting = "Hello, World!";
module_param(greeting, charp);
MODULE_PARM_DESC(greeting, "Custom greeting message");

int hello_init(void) {
    printk(KERN_INFO "%s\n", greeting);
    return 0;
}

void hello_exit(void) {
    printk(KERN_INFO "Module removed.\n");
}
  • module_param() declares a parameter. The second argument specifies the type (charp for a string).
  • Use insmod hello.ko greeting="Goodbye!" to pass the parameter at load time.

Compiling the Module

Create a Makefile in the same directory:

obj-m += hello.o

Compile the module using the kernel build system:

make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
  • This links against the currently running kernel's source tree. Ensure the kernel headers match your kernel version.

Loading and Testing the Module

Load the module with insmod:

sudo insmod hello.ko greeting="Welcome!"

Check the kernel log:

dmesg | tail

Output:

[12345.6789] Welcome!
[12345.6789] Module removed.

Unload the module:

sudo rmmod hello

Key takeaways

  • Every module must define init and exit functions for lifecycle management.
  • printk() is used for debugging, but messages are not visible in /var/log/messages by default—use dmesg or configure log levels.
  • Module parameters enable runtime configuration via insmod or modprobe.
  • Compilation requires linking against the kernel source tree to ensure compatibility.