Thursday, January 18, 2007

the simplest Linux kernel module

I just wrote the simplest possible kernel module. Here it is (hello_world.c):

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

MODULE_LICENSE ("GPL");

static int __init hello (void) {
printk (KERN_ALERT "Hello World!\n");
return 0;
}

static void goodbye (void) {
printk (KERN_ALERT "Good Bye!\n");
}

module_init(hello);
module_exit(goodbye);

This is taken from the Network Security Tools, excellent book for hackers. You can build the module by 1) creating a Makefile with this line: obj-m +=hello_world.o
2) running make -C /usr/src/linux-`uname -r` SUBDIRS=$PWD modules

The module will be called hello_world.ko and you can load it by becoming root and doing

insmod ./hello_world.ko

This should print "Hello World" if you're doing this from a console (not X), but if you're using X, you should see this message logged in /var/log/messages

You can unload the module by doing (as root)

rmmod hello_world

Again, if you're on X, the "good bye" message will be in /var/log/messages
Now I just have to find the time to get a proper kdbg patch...

No comments: