Linux Kernel Module Code
Install Build tools:
sudo apt update
sudo apt install build-essential linux-headers-$(uname -r)
Create the module:
hello.c#include <linux/init.h> // Initialization macros #include <linux/module.h> // Core headers for modules #include <linux/kernel.h> // Kernel logging MODULE_LICENSE("GPL"); // License type MODULE_AUTHOR("Silly Snail"); // Author of the module MODULE_DESCRIPTION("A Simple Hello World Kernel Module"); MODULE_VERSION("1.0"); // Function executed when module is loaded static int __init hello_init(void) { printk(KERN_INFO "Hello, Kernel! Module Loaded.\n"); return 0; // Return 0 on success } // Function executed when module is unloaded static void __exit hello_exit(void) { printk(KERN_INFO "Goodbye, Kernel! Module Unloaded.\n"); } // Register module entry and exit points module_init(hello_init); module_exit(hello_exit);
Create a make file:
Makefileobj-m += hello.o # Compile hello.c into hello.ko (kernel object) KDIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) all: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean
Build and test it:
make
sudo insmod hello.ko
lsmod | grep hello
sudo dmesg | tail -10
sudo rmmod hello
dmesg | tail -10
make clean