2009/05/01

The Hello kernel module in Ubuntu 9.04

Prepare hello.c and Makefile as below for the first kernel module. hello.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>

/*
 use insmod to load module
 msg log to /var/log/messages
 use tail or lsmod to check
*/

static int __init my_init(void)
{
  printk("<1> Hello, Orz...\n");
    return 0;  /* if -1, operation not permitted */
}


/* use rmmod to unload module */
static void __exit my_exit(void)
{
  printk("<1>Bye, Orz...\n");
}

/* register user's init/exit functions */
module_init(my_init);
module_exit(my_exit);

/*
 compile with
   $ make -C /lib/modules/`uname -r`/build/ M=`pwd` modules
   remarks: -C, change directory before read user Makefile
             M, path to module source
*/
Makefile
obj-m += hello.o

all:
         make V=1 -C /lib/modules/`uname -r`/build M=`pwd` modules
clean:
         make -C /lib/modules/`uname -r`/build M=`pwd` clean
To make the kernel module $ make Load the kernel $ insmod hello.ko Check whether the module is loaded $ lsmod Module Size Used by hello 9344 0 : Unload the module $ rmmod hello Check the printk messages $ cat /var/log/messages | grep Hello
May  1 22:24:14 chanyenping kernel: [ 6130.384230] [Hello] Initalizing...
May  1 22:24:35 chanyenping kernel: [ 6151.456077] [Hello] Bye !

沒有留言: