Every Journey starts with a single step. So does the kernel programming. In Linux kernel many vital functions are arranged in the form of modules, that can be loaded when needed. Here a small module that prints “Hello World” when loaded into the kernel is made. When the module is removed from the kernel, “Good Bye” is printed.
Here is the code for FirstModule.c :
/*
* Hello world Module
*
* Manish Shrestha, June 5, 2008
* */
#include
#include
/*init_module is called whenever the module is loaded into the kernel*/
int init_module(void)
{
printk(”Hello World from Manish Shrestha\n”);
return 0;
}
/*clean_module is called whenever the module is unloaded from the kernel*/
void cleanup_module(void)
{
printk(KERN_INFO “Good Bye From Manish.\n”);
}
In order to compile the module, create a Makefile with the following content:
obj-m += FirstModule.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
Now run the makefile by running the following command in the shell as root user:
#make
This will create a module file FirstModule.ko. To inset this into the kernel module issue the following command:
[root@localhost module]# /sbin/insmod FirstModule.ko
To check if the module has really been inserted and the init_module() has been called, use dmesg and lsmod commands.
[root@localhost module]# dmesg | tail
Hello World from Manish Shrestha
[root@localhost module]# /sbin/lsmod
Module Size Used by
FirstModule 5376 0
vfat 13249 0
Now lets use rmmod and see if the cleanup_module() has been really called and the module has been removed from the kernel:
[root@localhost module]# /sbin/rmmod FirstModule
[root@localhost module]# dmesg | tail
…
Hello World from Manish Shrestha
Good Bye From Manish.
Issuing the /sbin/lsmod command will also tell reveal that there is no module name FirstModule in the kernel.
Note: The article can also be found in my Technical Blog site at http://tblog.melectrosoft.com/ . You can also visit my simple site at http://www.melectrosoft.com/.
Thank you all