Team LiB
Previous Section Next Section

7.1. Hello World

To learn the basics of writing LKMs, first we'll attempt to write a simple module that prints Hello World! to the console when loaded, and Goodbye! when unloaded. To write code for the module, include the required header files:

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

The 2.6 Linux kernel warns you if a module whose source code is not under the GPL is loaded. This is because the Linux kernel is under the GPL license, and the kernel maintainers insist that all code loaded into the kernel should also be under the GPL license. To prevent the warning message from showing, you will need to classify your module code under the GPL license and include the following directive:

MODULE_LICENSE ("GPL");

Next, define hello( ), which simply prints the string Hello World! to the console using printk( ):

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

Now define goodbye( ), which prints the string Goodbye! to the console:

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

Next set hello( ) and goodbye() to be the initialization and exit functions, respectively. This means hello( ) will be called when the LKM is loaded, and goodbye( ) will be called when the LKM is unloaded:

module_init(hello);
module_exit(goodbye);

7.1.1. hello_world.c

Following is the source code of our hello_world LKM:

#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);

7.1.2. Compiling and Testing hello_world

To compile the preceding source code, create the following makefile:

obj-m += hello_world.o

Compile by running make:

[notoot]$ make -C /usr/src/linux-`uname -r` SUBDIRS=$PWD modules
make: Entering directory `/usr/src/linux-2.6.8
  CC [M]  /tmp/lkms/hello_world.o
  Building modules, stage 2.
  MODPOST
  CC      /tmp/lkms/hello_world.mod.o
  LD [M]  /tmp/lkms/hello_world.ko
make: Leaving directory `/usr/src/linux-2.6.8

Run the insmod tool to load the module:

[root]# insmod ./hello_world.ko
Hello World!

List loaded LKMs using the lsmod tool:

[root]# lsmod
Module                  Size  Used by
helloworld              2432  0

Remove the module by using the rmmod tool:

[root]# rmmod hello_world
Good Bye!

    Team LiB
    Previous Section Next Section