- There are two main functions to insert and remove module into and from kernel. Those function are init_module() and cleanup_module()
- Whatever module you want to insert write code for that in init-module() and write code which do cleaning operation of your module in cleanup_module().
- Write make file to build your module
- Build you module using "make"
- Once your code is error free insert the module using command "insmod module.ko". This will execute code and print log messages from init_module()
- Remove your module from kernel using "rmmod module". This will execute code and print log messages from cleanup_module()
- If in case messages are not displayed on promt you can use "dmesg" command which will print all kernel messages. Lets have a look on simple example:
int init_module()
{
printk(KERN_INFO "Hello World\n");
return 0;
}
void cleanup_module()
{
printk(KERN_INFO "GoodBye\n");
}
save this code in file hello.c
Now write make file to compile this code:
KDIR:=/lib/modules/$(shell uname -r)/build
obj-m:=hello.o
default:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
clean:
$(RM).*.cmd*.o*.ko -r .tmp*
Save this code as Makefile in the same folder in which your hello.c is there. Now come to prompt
$make
This will create hello.ko and many other files but we will concentrate on hello.ko file
$insmod hello.ko
This will insert your module hello.c in kernel. If you want to check whether it loaded into kernel or not verify it using "lsmod | more" command. It will display your module hello on top and many oher kernel modules below it. It will also print "Hello World" on the screen. If its not then type "dmesg" command to see kernel log messages.
If you wnat to remove yor module from kernel type
$rmmod hello
Now check whether your module is removed from kernel using lsmod again. Its not there.