Hello World! Kernel Module
Table of contents
Hey everyone! This script guides you through building and running a simple "Hello World" kernel module in Linux. We'll follow the approach explained in Robert Love's "Linux Kernel Development" and refer to the official Kernel Documentation (https://www.kernel.org/doc/html/latest/index.html).
Here are my solutions to the Eudyptula Challenge: https://github.com/pro-utkarshM/Kernel-Carnival.
Preparation:
Grab a mug of coffee, recall any regrets from your previous semester ( Organizational Behaviour could have saved you!), and let's jump in with some newfound experience!
The "Hello World" Module:
- Code:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
static int hello_init(void) {
printk(KERN_DEBUG "Hello World!\n");
return 0;
}
static void hello_exit(void) {
printk(KERN_DEBUG "See you later.\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("projects.utkarshMaurya@gmail.com");
MODULE_DESCRIPTION("Just a module");
obj-m += helloworld.o
KDIR := /lib/modules/$(shell uname -r)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
- Compilation:
Use the make
command in the module directory.
- Loading:
Run sudo insmod FILE_NAME.ko
after replacing FILE_NAME
with your actual module file name (e.g., insmod helloworld.ko
).
- Viewing Output:
Check kernel messages with sudo dmesg | grep tail
.
Understanding the Process:
module_init
andmodule_exit
macros define functions to run when loading and unloading the module.The
printk
function logs messages to the kernel ring buffer.
Example:
Here's a demonstration of compiling and running the module:
$ ls
Kbuild Makefile modul.c
$ make
make -C /lib/modules/`uname -r`/build M=`pwd`
# ... compilation output ...
$ ls
built-in.o Kbuild Makefile modul.c Module.markers
modules.order Module.symvers modul.ko modul.mod.c
modul.mod.o modul.o
$ insmod modul.ko
$ dmesg | tail -1
Hi
$ rmmod modul
$ dmesg | tail -2
Hi
Bye
Additional Information:
- For a list of loaded modules, use
lsmod
or explore/proc/modules
and/sys/module
directories.
I hope it's easier to understand and follow!
Let me know if you have any questions about specific parts or need further clarification.