"Hello World!" Linux Kernel Module

What is a kernel module?

Kernel modules are the pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.

The device drivers, networking stack; for almost everything you will find a module in the kernel.

To use the kernel module there are three specific tools/commands that you will need.

$ lsmod    # List all existing modules in the kernel.
$ insmod   # Insert the new module in the kernel.
$ rmmod    # remove the inserted module.

Let’s build our own “Hello World!” kernel module

Dependencies.

what we need (on Fedora).

The code.

#include <linux/module.h>     // included for all kernel modules
#include <linux/kernel.h>     // included for KERN_INFO
#include <linux/init.h>       // included for __init and __exit macros

MODULE_LICENSE("GPL");        // The license  under which the module is distributed.
MODULE_AUTHOR("Girish Joshi");// The author of the module.
MODULE_DESCRIPTION("HelloWorld Linux Kernel Module."); // The Description of the module.


// This function defines what happens when this module is inserted into the kernel.
// ie. when you run insmod command.
static int __init hello_init(void)
{
    printk(KERN_INFO "Hello world!\n");
    return 0;    // Non-zero return means that the module couldn't be loaded.
}

// This function defines what happens when this module is removed from the kernel.
// ie.when you run rmmod command.
static void __exit hello_cleanup(void)
{
    printk(KERN_INFO "Cleaning up module.\n");
}

module_init(hello_init);      // Registers the __init function for the module.
module_exit(hello_cleanup);   // Registers the __exit function for the module. 

Let’s save this file as hello.c

Building the module.

The makefile for building this module looks like:

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

to build the module you will have to run:

$ make

to insert/load the module into the kernel:

$ insmod hello.ko

to check if the __init function of the module is called or not:

$ dmesg | grep "Hello World"

to remove this module from the kernel:

$ rmmod hello

to check if __exit function of the module is called or not run:

$ dmesg | grep "Cleaning up the module"

So this is the template for building a linux kernel module.