Kernel modules are applications that work a little different than regular applications. These don't hae a main function that woill be the entry point of the application, instead they respond to events.
Kernel Modules are applications that extends the kernel and they can be loaded and unloaded on demand without having to rebuild the entire kernel.
The below commands will allow you to manage the loadable kernel modules:
List the loaded modules:
lsmod
Information about specific modules:
modinfo modulename
To install a module:
insmod modulename
To unload a module:
rmmod modulename
You can also use modprobe to load a module with all it's dependencies
modprobe modulename
Or unload:
modprob -r modulename
Load a module with parameters
modprobe modulename parametername=parameter_value
or
insmod modulename parametername=parameter_value
include <linux/module.h>
include <linux/init.h>
include <linux/kernel.h>
static int __init ernesto_init(void)
{
pr_info("Initializing Ernesto's Loadable Kernel Module\n");
return 0; // Return 0 when the load was successful.
}
static void __exit ernesto_exit(void)
{
printk(KERN_INFO "Finalizing Ernesto's Loadable Kernel Module\n");
}
module_init(ernesto_init);
module_exit(ernesto_exit);
MODULE_AUTHOR("Ernesto Maldonado Thomas");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Test Loadable Kernel Module development");
- The
#include <linux/module.h>
is required for using themodule_init()
andmodule_exit()
functions. - The
#include <linux/init.h>
is required for the functions - The
#include <linux/kernel.h>
is required forKERN_INFO
- The
__init
is used to release the memory used by the function and is recommended because of the limited memory available for the kernel modules. - The
module_init()
function registers the function that will be executed during the load of the module. - The
module_exit()
function registers the function that will be executed when the module is unloaded.
To build the module make sure to have the linux headers installed:
On Arch:
sudo pacman -Syu && sudo pacman -S linux-headers
On Debian/Ubuntusudo apt update && sudo apt install linux-headers-$(uname -r)
On CentOS or RHEL7:yum install kernel-devel
On Fedora:dnf install kernel-devel
To build the module use the below Makefile:
obj-m += hello-1.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
This will produce a file (In this case ernesto.ko) extension .ko is a kernel object.
to load the Kernel:
insmod ernesto.ko
Rheck dmesg
to see the printk()
and pr_info()
results.
printk() and pr_info() will both result in the same I will elabore more later in future updates of this document
Run modinfo
to list the AUTHOR, LICENSE, and some other information about the Kernel Module.