Wednesday 21 September 2011

Linux kernel module programming

                                                           A kernel module is a piece of code which can be dynamically loaded or unloaded from the system to extend its functionality . There is no need to compile the whole kernel source code for adding a single functionality. also you need not reboot the system after adding the module . This is one of the features of the micro kernel architecture.
so let us write our conventional starting code .
Hello world module.
#include
int int_module(void)
{
   printk(" Hello, world \n");
   return 0;
}

void cleanup_module(void)
{
   printk(" bye bye world \n");
}
as you can see in the code above there are two functions
1) init_module .
2) cleanup_module
init_moudule is some what like the main fuction in the usual code this is where the kernel module starts working .It is called immidiately after insmod command is executed.
The cleanup_module is the exit function it is called immidiately after the rmmod comman is executed.
As given in the code above , we are using printk function instead of printf function .Heare our module is going to run in kernel space not as a user program so we don't use the user library functions so we need the kernels own printf and that is our printk function .



Compiling the kernel module
for compiling the kernel module you need to compile the kernel module. For this you need to create a make file

Makefile:
obj-m: hello-world.o


now you need to execute the command
make -C /usr/src/linux-3.0/ M=`pwd` modules
After executing the above command do an ls in the current directory you can see that there will be a file named hello-world.ko

Loading the kernel module to the running kernel.

To load the kernel to the currently running kernel we need to use some commands

commands for loading

1)insmod
2)modprob

command for unloading the module

1)rmmod

now use the command
insmod hello-world.ko
if you didnot see a print

No comments:

Post a Comment