next up previous contents index
Next: Makefiles for Kernel Modules Up: Linux Kernel Module Programming Previous: For version 1.1.0

  
Hello, world

When the first caveman programmer chiseled the first program on the walls of the first cave computer, it was a program to paint the string `Hello, world' in Antelope pictures. Roman programming textbooks began with the `Salut, Mundi' program. I don't know what happens to people who break with this tradition, and I think it's safer not to find out.    

A kernel module has to have at least two functions: init_module which is called when the module is inserted into the kernel, and cleanup_module which is called just before it is removed. Typically, init_module either registers a handler for something with the kernel, or it replaces one of the kernel function with its own code (usually code to do something and then call the original function). The cleanup_module function is supposed to undo whatever init_module did, so the module can be unloaded safely.    

ex hello.c   

 
/* hello.c 
 * Copyright (C) 1998 by Ori Pomerantz
 * 
 * "Hello, world" - the kernel module version. 
 */

/* The necessary header files */

/* Standard in kernel modules */
#include <linux/kernel.h>   /* We're doing kernel work */
#include <linux/module.h>   /* Specifically, a module */



/* Deal with CONFIG_MODVERSIONS */
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#endif        



/* Initialize the module */
int init_module()
{
  printk("Hello, world - this is the kernel speaking\n");

  /* If we return a non zero value, it means that 
   * init_module failed and the kernel module 
   * can't be loaded */
  return 0;
}


/* Cleanup - undid whatever init_module did */
void cleanup_module()
{
  printk("Short is the life of a kernel module\n");
}



 


1999-05-19