Pick a Free OS

User login

Navigation

Introduction to Linux kernel modules

Let us now program a simple module to review its life cycle. The init_module is called when the module is inserted into the kernel where as the cleanup_module is called just before removing it from the kernel. In the following program, the init_module and the cleanup_module functions are demonstrated.

/* Simple Linux kernel module Feb'2001

#include

#include

#if CONFIG_MODVERSIONS==1

#define MODVERSINS

#include

#endif

/ initialise the module /

int init_module()

{

printk("init_module invokedn");

printk("the message is printed from the kernel spacen");

/ if the non zero value is returned, then it means that the init_module failed and the kernel module can't be loaded /

return 0;

}

/ cleanup / end of module life cycle */

void cleanup_module()

{

printk("cleanup_module invokedn");

printk("module is now going to be

unloaded from the kerneln");

}

Compile the above program using the following:

#gcc -Wall -DMODULE -D__KERNEL__ -DLINUX -O -c simpelModule.c

Run the compiled module using the following:

#insmod simpleModule.o

Remember, you have to run the above command from the Linux shell at raw console (not from the console in Xwindows environment) at root login.

Now check the status of the module using

#lsmod

Then remove the module using

#rmmod simpleModule

If you have not seen any of the module-initiated console printing (implemented using `printk') about the status of the module, use the following command to see the kernel messages.

dmesg | less

In the above, commands insmod, lsmod and rmmod are used to load and unload modules to the Linux kernel. The details are discussed in the following section.

Loading modules

insmod loads the `loadable kernel modules' in the running kernel. insmod tries to link a module into the running kernel by resolving all the symbols from the kernel's exported `symbol table'.