Linux Kernel Modules
Tutorial to insert & remove a Loadable kernel module [LKM].
Writing a kernel module
Create directory ‘linux-kernel-module’
$ mkdir linux-kernel-modules
$ cd /linux-kernel-modules
Create a file ‘hello.c’
$ touch hello.c
Write module program in ‘hello.c’ file.
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
static int __init print_hello(void){
printk(KERN_INFO "Loading hello module...\n");
printk(KERN_INFO "hello world\n");
return 0;
}
static void __exit exit_hello(void){
printk(KERN_INFO "bye bye kernel !\n");
}
module_init(print_hello);
module_exit(exit_hello);
Explaination,
- writing kernel module requires two important functions i.e. ‘__init’ & ‘__exit’.
- ‘__init’ function is called when the modules is loaded to the kernel.
- ‘__exit’ function is called when the module is removed from the kernel.
- ‘printk()’ function in C language is similar to ‘printf()’, but prints message to the ‘kernel log’ .
Compiling kernel module
- we are using ‘make’ program to compile our kernel module.
- we need to create a file named ‘Makefile’
$ touch Makefile
- with following set of commands
obj-m += hello.o
all:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) clean
- Now compile our kernel module by executing ‘make’ .
$ make
Load the module to kernel.
- once the ‘make’ is successful, ‘hello.ko’ file is create.
- ‘.ko’ is the kernel object.
- insert this ‘.ko’ object to the kernel by,
$ sudo insmod hello.ko
Display kernel log
$ dmesg
Unload or remove kernel module we inserted,
$ sudo rmmod hello
- To display again kernel log
$ dmesg
Support
To update the web page click here