Pages

Friday, June 26, 2015

Linux Kernel Module - Creating, Inserting and Removing Kernel Object

Consider the following C program stored in the file simple_module.c


#include <linux/init.h>
#include <linux/module.h>

int simple_module_init(void){
  printk(KERN_ALERT "Inside the init function");
  return 0;
}

void simple_module_exit(void){
  printk(KERN_ALERT "Inside the exit function");
}

module_init(simple_module_init);
module_exit(simple_module_exit);
The above example is the simplest example of a kernel module. It has an init and an exit function. The init function is called when the module is initialized and the exit function is called when the module is removed.

To run this program we create a Makefile which is as follows:

obj-m := simple_module.o

To compile this function we run the following command,

"make -C /lib/modules/$(uname -r)/build M=$PWD modules", where C gives the directory of the build and M means the module, PWD means the reference files are in the present directory.

When this command is run, it creates a simple_module.ko file, ko = kernel object.

To load this module into the kernel, the command is :

sudo insmod simple_module.ko

We can see if the module is loaded using the following command:

lsmod

To remove the module from the kernel, we use the following command:

sudo rmmod simple_module

The log messages can be seen in /var/log/syslog or /var/log/messages.

Use the following command to see the tail of the file and follow the changes in file

tail -f /var/log/syslog