Linux Kernel Module Programming

Here’s a basic tutorial for beginners to add a custom module into their Linux kernel.

Modules are basically device drivers (as we call them in windows). As in windows operating system, drivers are needed to run a specific hardware, in Linux we have modules to serve that purpose. Let us go through the basic steps to add a custom module into your Linux Kernel Source.

1. Enter Your Linux source directory. Find out the version of your Linux kernel using uname –r command

To enter into your Linux source directory type

#sudo su (to gain admin privileges)

cd /usr/src/

In my case I have used cd/usr/src/Linux-4.0.1/

2. We need to create two files in the same directory

For that we make a folder named welcome in the Linux source directory. To make and enter the folder

Type #mkdir welcome && cd welcome in the same terminal and now you are in the directory usr/src/linux-4.0.4/welcome. Now we need to create two files in this directory

a) welcome.c

This file contains our custom module program which will perform some action when this module is called.

Type #gedit welcome.c in the same terminal and type the code below in welcome.c and save it.

b) Makefile

This file directs the make command, what actions are to be performed.

Type #Makefile in the same terminal and type the code below in Makefile and save it.

obj-m +=welcome.o

3. Now after we have created these two files. We need to compile and install the new module, we created above.

Type

In my case its

This might need 4-5 minutes depending on your system.

4. Now you need to install our new module.

Type the following command in the same terminal

5. Your new module has been successfully installed now. Now you need to insert the module in your Linux Kernel

Type the command insmod ./welcome.ko in the terminal and press the enter key.

Your module is successfully installed. To check this type #lsmod in your terminal and the first module would be named as welcome. If its not there, you need to re-check your steps.

6. Now to display the message your module holds upon initialization type #dmesg | tail in your terminal and press the Enter key

You’ll get the message Welcome, Ashish on your console.

7. Now if you want to unload this module type #rmmod ./welcome.ko and the module will disappear from the lsmod list

To check the message upon module unload you again need to type dmesg | tail on your terminal and you will get a message Goodbye, Ashish on your console.

Thus following the above few steps, you have successfully learnt how to add a custom module in Linux Kernel

I am pursuing my BTech in IT from MIT, Pune and am an enthusiastic Android Developer.

This content has been helpful to you?

Thanks for contributing!

Yes No