Pages

Wednesday, September 19, 2012

Make one simple kernel module using C programming language.

Today I will try to explain how to make a kernel module.
Basically, a kernel module it's one piece of code that can be loaded and unloaded into the kernel.
You can read about kernel modules from here.
Now, let's try to make a simple kernel module.
Writing your own module can be done if you know some basic rules.
First, about how to use modules.
Suppose you have a new module named kernelmoduletest.
How to load the module.
Just use this command in your module kernel folder:
#insmod kernelmoduletest.ko
Next, test the kernel module messages.
This can be done with:
#dmesg | tail
Also, you need to remove the kernel module.
$ rmmod kernelmoduletest 
ERROR: Removing 'kernelmoduletest': Operation not permitted
This means you need to have superuser rights. So use the sudo or su command.
Then use the rmmod command.
Know how to make the kernel module skeleton.
This is not very simple because you need to know many things about kernel and programming.
But you can try the test with some simple example like this example:
Create the c file named kernelmoduletest and add this source code:
#include <linux module.h="">
#include <linux kernel.h="">

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("kernelmoduletest");
MODULE_AUTHOR("Catalin George Festila/mythcat/catafest");

int init_module() {

    printk(KERN_INFO "Now I will initialize my  kernel module\n");

    printk(KERN_INFO "Test: Hello World !\n");

    return 0;
}

void cleanup_module() {

    printk(KERN_INFO "Bad!... kernel module unloaded.\n");
}</linux></linux>
Make a new file named Makefile.
Add this to tell how to compile the kernel module.
obj-m += kernelmoduletest.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
Compile your kernel module
Just use make command.
# make
...
  Building modules, stage 2.
  MODPOST 1 modules
...
make[1]: Leaving directory `/usr/src/linux-headers-2.6.31-14-generic'
If you test your module using the commands from the top of this tutorial, you can see that:

[14694.779227] Now I will initialize my  kernel module
[14694.779233] Test: Hello World !
[15049.825605] Bad!... kernel module unloaded.
If you have already made kernel modules and the subject it's interesting for you, send me an email.
Thank you. Regards.