Writing A Simple Linux Kernel Module

The first example that is always depicted in understanding any coding language (or kernel programming in our case) is to write the hello world example. Let us write a simple kernel program which outputs ‘hello’ and ‘goodbye’. 

Below is the sample code for the driver – it has comments placed to explain what each line is doing. Save the below code as first_code.c

The kernel module can be compiled by writing a simple Makefile. We will understand the Makefile in more detail in another article. The current Makefile will compile the code snippet. Place the first_code.c file and the Makefile in the same folder.

The Makefile is shown below

Run the “make  command” as shown below. The output of the make command is also shown below.

The Kernel module that is compiled is shown below.

So the first kernel module is compiled. Now , we need to load the kernel module into the Linux kernel. The following command “insmod” will achieve the feat. A user can also look at the “modprobe” command to load the module.

The “modprobe” command will look at the dependencies that the current module attempted to be inserted currently have, load all the dependencies and then attempt to load the current kernel module

The “insmod” command only tries to load the current module

When we check the dmesg log – we find that the entry point of the kernel module is entered

Do not worry about the error message. The error message only states that we tried to force load a module into the linux kernel which is not part of kernel source for this release. We can see that the “heloo” message is printed out indicating that the initialization code for the module was entered and the module was loaded.

If we want to confirm whether the module is loaded – execute the “lsmod” command. The lsmod command lists all currently loaded modules in the Linux kernel.

The “Used by” indicates whether any other module uses the current module. In the case of first_code module – no other module is using the first_code module.

In order to remove the module from the Linux Kernel – we can use the “rmmod” command.

The dmesg command shows that the de-init routine was invoked for the first_code module as the “gooodbye” message and the lsmod command no longer shows the  first_code module as being loaded.

As can be seen above – the “gooodbye message” is displayed by dmesg log and also the first_code module which was displayed at the beginning  when lsmod was invoked is no longer present.

Hence, with this article, we have written a simple kernel module, loaded it and unloaded the module.

The Next Step in writing a device driver for Linux



  1. Pingback: The Next Step in writing a device driver for Linux | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *