Skip to content

Day05 - Kernel Module Hello World


Objective

  • Build a Linux kernel module
  • Load and unload module
  • Observe kernel behavior via logs

Environment

  • Board: Raspberry Pi 5
  • OS: Debian (Raspberry Pi OS Lite)
  • Architecture: arm64

Step 1 — Create Source Code

File: hello.c

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

static int __init hello_init(void)
{
printk(KERN_INFO "Hello, Kernel Module Loaded!\n");
return 0;
}

static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, Kernel Module Unloaded!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Chia-Wei Chien");
MODULE_DESCRIPTION("Simple Hello World Kernel Module");

/* End of File */

Step 2 — Create Makefile

obj-m += hello.o

KDIR := /lib/modules/$(shell uname -r)/build
PWD  := $(shell pwd)

all:
$(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean

# End of File

Step 3 — Build Module

make

Output:

  • hello.ko

Step 4 — Insert Module

sudo insmod hello.ko

Step 5 — Check Kernel Log

dmesg | tail

Expected:

Hello, Kernel Module Loaded!

Step 6 — Remove Module

sudo rmmod hello

Step 7 — Verify Removal

dmesg | tail

Expected:

Goodbye, Kernel Module Unloaded!

Step 8 — Inspect Module

lsmod
modinfo hello.ko

Observations

  • Module is dynamically inserted into kernel
  • printk outputs to kernel log
  • No reboot required

Key Learnings

  • Kernel modules run in kernel space
  • .ko is a loadable object
  • insmod / rmmod control module lifecycle
  • Debugging relies on dmesg

Common Issues

1. Missing kernel headers

Error:

No such file or directory: /lib/modules/.../build

Solution:

sudo apt install linux-headers-$(uname -r)

2. Permission denied

Use:

sudo insmod hello.ko

Next Step

  • Implement character device driver
  • Add read/write interface
  • Connect user space with kernel