View on GitHub

linux-kernel-modules

linux-kernel-modules example

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,

Compiling kernel module

$ touch Makefile
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
$ make

Load the module to kernel.

$ sudo insmod hello.ko

Display kernel log

$ dmesg

Unload or remove kernel module we inserted,

$ sudo rmmod hello
$ dmesg

Support

To update the web page click here