Write a Linux kernel module to collect information of curren
Solution
Kernel modules are piece of code, that can be loaded and unloaded from kernel on demand.
Kernel modules offers an easy way to extend the functionality of the base kernel without having to rebuild or recompile the kernel again. Most of the drivers are implemented as a Linux kernel modules. When those drivers are not needed, we can unload only that specific driver, which will reduce the kernel image size.
The kernel modules will have a .ko extension. On a normal linux system, the kernel modules will reside inside /lib/modules/<kernel_version>/kernel/ directory.
Earlier we discussed how to compile a kernel from the source.
This tutorial explains how to write a Kernel module using a simple Hello World example.
I. Utilities to Manipulate Kernel Modules
1. lsmod – List Modules that Loaded Already
lsmod command will list modules that are already loaded in the kernel as shown beblow.
2. insmod – Insert Module into Kernel
insmod command will insert a new module into the kernel as shown below.
3. modinfo – Display Module Info
modinfo command will display information about a kernel module as shown below.
4. rmmod – Remove Module from Kernel
rmmod command will remove a module from the kernel. You cannot remove a module which is already used by any program.
5. modprobe – Add or Remove modules from the kernel
modprobe is an intelligent command which will load/unload modules based on the dependency between modules. Refer to modprobe commands for more detailed examples.
II. Write a Simple Hello World Kernel Module
1. Installing the linux headers
You need to install the linux-headers-.. first as shown below. Depending on your distro, use apt-get or yum.
2. Hello World Module Source Code
Next, create the following hello.c module in C programming language.
