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

Get Network Security Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.