Hello World Kernel Module
This is an example of a Hello World Kernel Module. Found many tutorial about this in internet. My aim is to write a minimal one and explain some of the basic concepts. Kernel module is a piece of code which we can insert into the kernel on the fly. Our module just print "Hello World". Since it is a "Kernel Module", it wont print in the shell. So we wont have any output when we run this code. But we can see the output in the log maintained by the Operating System.
So our program is hello.c.
#include<linux/module.h>
int hello_init(void)
{
printk(KERN_ALERT "Hello World\n");
return 0;
}
void hello_exit(void)
{
printk(KERN_ALERT "Good Bye\n");
}
module_init(hello_init);
module_exit(hello_exit);
This program consists of two user defined functions hello_init() and hello_exit(). The last lines module_init(hello_init) and module_exit(hello_exit) tells the module that call the functions hello_init() and hello_exit() when the module is loaded and unloaded respectively. So, when the module is loaded Hello World is printed and when exited Good Bye is printed.
Kernel documentation says that we can compile the module using the command
jestinjoy@debian:~/hello$ make -C /lib/modules/`uname -r`/build M=$PWD
If everything works fine this will create a file called hello.ko among some other files. If it doesn't work, the most probable chance is you dont have kernel-headers (Kernel module needs seperate header files for compilation like module.h and is not installed by default) installed. You can install it by going to synaptic package manager or using the tool apt-get. The package name is linux-headers. My running kernel is 3.2.0-4-amd64
jestinjoy@debian:~/hello$ uname -a
Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.41-2 x86_64 GNU/Linux
So I have installed the package linux-headers-3.2.0.4-amd64
To insert the module to the kernel, as root you can do the command insmod.
root@debian:/home/jestinjoy/hello# insmod hello.ko
This command just returns. To view the output you can type the command dmesg, which prints the system log contents.
jestinjoy@debian:~/hello$ dmesg
....
....
....
[ 3015.906581] Hello World
You can remove the module using the commands rmmod [No need to give hello.ko when removing].
root@debian:/home/jestinjoy/hello# rmmod hello
jestinjoy@debian:~/hello$ dmesg
....
....
....
[ 3015.906581] Hello World
[ 3287.082234] Good Bye