Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 837 of 93611. Introduction to Embedded LinuxFree lesson

Writing a Minimal Kernel Module

Learners will write a basic C source file containing module initialization and cleanup functions to understand the fundamental structure of kernel code.

In this lesson, you will learn the essential anatomy of a Linux kernel module and how to define its entry and exit points.

The Kernel Module Structure

Unlike a standard C program that starts execution at main(), a Linux kernel module is an object file that the kernel dynamically links into its own address space at runtime. Because it runs in kernel space (Ring 0), it lacks access to standard C library functions (like printf), relying instead on kernel-provided alternatives like printk.

To integrate your code, you must define two specific functions: one that runs when the module is inserted into the kernel, and one that runs when it is removed.

Defining Entry and Exit Points

We use specific macros to register these functions so the kernel knows how to manage our code's lifecycle. Here is a minimal implementation:

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

static int __init my_module_init(void) {
    printk(KERN_INFO "Hello, Kernel World!\n");
    return 0; // Return 0 to indicate successful loading
}

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

module_init(my_module_init);
module_exit(my_module_exit);

MODULE_LICENSE("GPL");

Understanding the Mechanics

  1. module_init and module_exit: These macros register your functions. The kernel calls the init function during insmod, and the exit function during rmmod.
  2. __init and __exit: These are optimization tags. The __init tag tells the kernel that the function is only used during initialization, allowing the memory to be reclaimed after the module is loaded.
  3. printk: This is your primary diagnostic tool. Because the kernel is separate from the user-space terminal, printk logs messages to the kernel ring buffer, which you can view using the dmesg command.

By defining these boundaries, you transform a block of code into a functional piece of the operating system, allowing you to manipulate hardware and system resources at the most privileged level.

Key Takeaway: A minimal kernel module acts as a plugin for the Linux kernel, using registration macros to define specific startup and shutdown logic that integrates directly into the core operating system.