Simple Linux Kernel Module Programming

The OS:

  • Xubuntu 18.04

Requirements

We need to install the following package first.

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

The uname -r outputs the kernel version of your system.

Then, we make a directory and cd into there.

mkdir helloworld
cd helloworld

You can do this in your home directory.

Create files

1. helloworld.c

#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void) 
{
    printk(KERN_INFO Hello, worldn);
    return 0;
} 
void cleanup_module(void)
{
    printk(KERN_INFO Bye, worldn);
}
  • module.h is needed for every kernel module.
  • kernel.h defines macros such as KERN_INFO.
  • We print our messages using printk, which can be viewed by typing dmesg in your terminal.

2. Makefile

KER = $(shell uname -r) 
PWD = $(shell pwd) 
obj-m += helloworld.o 
all:
    make -C /lib/modules/$(KER)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(KER)/build M=$(PWD) clean

Having the above done, now we can type make. And you can notice there are some files created in our current directory by typing ls.

Insert module

Now we can insert our module by

insmod helloworld.ko

and use dmesg to check the message printed by our module when loaded.

Remove module

And then we can remove our module by

rmmod helloworld

and use dmesg to check the message printed by our module when unloaded.

Leave a Reply

Close Menu