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. TheKERN_INFOlevel ensures the message appears in/var/log/syslogor viadmesg.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 (charpfor 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:
Compile the module using the kernel build system:
- 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:
Check the kernel log:
Output:
Unload the module:
Key takeaways¶
- Every module must define
initandexitfunctions for lifecycle management. printk()is used for debugging, but messages are not visible in/var/log/messagesby default—usedmesgor configure log levels.- Module parameters enable runtime configuration via
insmodormodprobe. - Compilation requires linking against the kernel source tree to ensure compatibility.