Hello, World -- Linux kernel modules

Get started

  • Ubuntu 20.04 LTS
  • Text Editor (VSCode, Vim, Emacs etc)

Declare to be a Linux Kernel module

You don't.
By running insmod xxxx.ko, you are declaring it to be a Linux kernel module, so there's nothing special compared with normal C programs.

Life Cycle

  • module_init
  • module_exit

When a module is inserted, kernel will call module_init() in the module.
When a module is removed, kernel will call module_exit() in the module.

hello.c

#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/init.h>
static int __init hello_init(void)
{
    printk(KERN_INFO "Hello, World!\n");
    return 0;
}
static void __exit hello_exit(void)
{
    printk(KERN_INFO "Bye!\n");
}
module_init(hello_init);
module_exit(hello_exit);

Makefile

In Linux kernel, we use Makefile rather than Cmake or any other build tools.

obj-m := hello.o  
KERNELBUILD :=/lib/modules/$(shell uname -r)/build  
default:  
	make -C $(KERNELBUILD) M=$(shell pwd) modules  
clean:  
	rm -rf *.o *.ko *.mod.c .*.cmd *.markers *.order *.symvers .tmp_versions

Compile

run make

Watch your dmesg

run dmesg -wH in a separate terminal

Insert module

run insmod hello.ko
You will get Hello, World! in dmesg.

Remove module

run rmmod hello
You will get Bye in dmesg.

Publish At: Author:Aiden Leong

Read more posts by this author

comments powered by Disqus