Wednesday, June 25, 2014

Hello Kernel

In this post we shall be writing a kernel module, which would cause the kernel to print our messages to the kernel log buffer. we shall not be looking deeper into the kernel buffer or the particular commands as that would be stretching this post too long. this is just a jump-start.

The kernel log is available through this command.
sudo dmesg
 
If you look at the messages already printed, they will be more often than not by the drivers , insert and remove a pen drive and run the command again, you will see some messages being printed. I would now advise to clear the kernel log buffer by running the following command.
sudo dmesg -c
 
now if you run the “dmesg” command again, you will see nothing or very minimal data s the old entries have been cleared and fresh entries are being put up.
let’s make the module now, do this task inside a directory you create, I named mine as “test” and the file as test.c. The contents of the file are as follows.

#include <linux/init.h>
#include <linux/module.h>

static int my_init(void){
printk("Hello world");
return 0;
}

static void my_exit(void){
printk("bye-bye");
}

module_init(my_init);
module_exit(my_exit);
 
now in the same directory make a file called Makefile and the contents of the makefile should be these.
obj-m := test.o
 
That’s it… now we run the command to compile our module. The command is as follows
make -C <linux-source-dir>  M=$PWD modules
 
if the compilation is succesful you will have a file named test.ko in the directory. we need to load it by using the insmod command.
sudo insmod test.ko
 
now see the kernel log by
dmesg
 
you would see the two messages “hello world” and “bye-bye”. It is finally done now, you have made the kernel print out a custom message for you.
There would have been many questions on the way but no worries all would be clear with some efforts. The strange make command, the new commands like “insmod” “dmesg” are real simple and can be understood with a simple google search. for the serious minds do read “Linux device drivers by greg kroah hartman” and “Linux kernel development by Robert love” the two very good books that i have always referred to. any more questions? do comment.. more than happy to help.

1 comment: