How to add a new Linux Kernel Module (LKM)

To demonstrate, let us goto a simple “Hello World” as a module and inserted in to the kernel

Step 1
Open any editor like vi or gedit in a shell prompt and the type the following
/* Name of the file is hello.c */
#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void)
{
printk(KERN_INFO “Hello world.n”);
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO “Goodbye worldn”);
}


The above is a simple C program that displays “Hello world” when the module is inserted and displays “Goodbye world” when the module is removed.
Step 2
The program can be compiled using gcc compiler in the shell prompt itself, but we need to write the commands twice or more. So to compile shortly let us write a makefile to compile the above program
The make file should be named as Makefile (See the First letter M is uppercase and there should not be any space between Make and file)
Copy and paste the following lines in an editor (vi or gedit)
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
Step 3
after this, execute the following command
# make
You will get the following output which indicates there is no error
make -C /lib/modules/2.6.27.5-117.fc10.i686/build M=/home/pradeepkumar/lsp modules
make[1]: Entering directory `/usr/src/kernels/2.6.27.5-117.fc10.i686′
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/kernels/2.6.27.5-117.fc10.i686′
The make command creates new set of files like hello.ko, hello.mod.o, modules.order, etc
Step 4
The .ko indicates it is a kernel object, but ordinary C compiler generates only an object file..
go to the shell prompt (open the terminal) execute the command one by one
# su
The above command waits for the root password, please provide the password
# insmod
inserting the module
# lsmod
listing all the modules running under the kernel, you can see the first module will be listed as hello
# dmesg
you can see thelast line says hello world
# rmmod
removing the module
# dmesg
you can see the last line says goodbye world
Like this we can write many modules and can be inserted to the kernel..

Popular Posts