Module is the piece of binary which can be inserted and removed, to and from Kernel dynamically. I mean into the current running kernel. I may demonstrate simple examples here,
Hello World Module
Module Creation
$ mkdir dummy
$ cd dummy/
$ vim hello.c
/* hello.c */
#include <linux/init.h>
#include <linux/module.h>
static int hello_init(void)
{
printk(KERN_ALERT “Jack and jill went upto hill\n”);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT “to fetch a pail of water\n”);
}
module_init(hello_init);
module_exit(hello_exit);
Here, hello_init() will get executed when this module is inserted, hello_exit() will get executed when the module is removed from Kernel.
Creation of Makefile
$ vim Makefile
obj-m += hello.o
KDIR = /usr/src/linux-headers-2.6.39-bpo.2-686-pae
all:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
rm -rf *.o *.ko *.mod.* *.symvers *.order
KDIR may point to path to linux kernel source directory, or only to kernel headers as I mentioned above.
Module Compilation
$ make
make -C /usr/src/linux-headers-2.6.39-bpo.2-686-pae SUBDIRS=/home/elcot/Desktop/Kernel_dd_training/felabs/linux/modules/dummy modules
make[1]: Entering directory `/usr/src/linux-headers-2.6.39-bpo.2-686-pae’
Building modules, stage 2.
MODPOST 1 modules
make[1]: Leaving directory `/usr/src/linux-headers-2.6.39-bpo.2-686-pae’
As a result various files generated as below,
hello.ko
hello.mod.c
hello.mod.o
hello.o
Module.symvers
modules.order
insmod (inserting module inside kernel)
$ sudo insmod hello.ko
dmesg (checking output of module inside kernel)
$ dmesg
<output truncated>
[ 8044.317993] r8169 0000:01:00.0: eth5: link down
[ 9387.926290] r8169 0000:01:00.0: eth5: link up
[13132.548674] r8169 0000:01:00.0: eth5: link down
[14226.600851] r8169 0000:01:00.0: eth5: link up
[15710.119776] hello: module license ‘unspecified’ taints kernel.
[15710.120782] Jack and jill went upto hill
hello_init() function is executed when module is inserted into the Kernel.
rmmod (to remove module from kernel)
$ sudo rmmod hello.ko
again, cheking with dmesg
$ dmesg
<output truncated>
[ 8044.317993] r8169 0000:01:00.0: eth5: link down
[ 9387.926290] r8169 0000:01:00.0: eth5: link up
[13132.548674] r8169 0000:01:00.0: eth5: link down
[14226.600851] r8169 0000:01:00.0: eth5: link up
[15710.119776] hello: module license ‘unspecified’ taints kernel.
[15710.120782] Jack and jill went upto hill
[15750.777030] to fetch a pail of water
hello_exit() function is called, when the module is removed..
Enjoy..!