Module loading
- C course
- Expert
- Lesson 7/47
- 5 min
Learn to load modules with insmod and rmmod.
Loading kernel modules
The Linux kernel can be extended at runtime with modules. A module is a piece of code loaded into kernel address space; no reboot required.
insmod modul.ko loads a module, rmmod modul removes it. lsmod lists loaded modules; modprobe also resolves dependencies. Modules have the .ko suffix and must be built for the running kernel. On load, the module's module_init function runs, so modules must be written carefully.
Module lifecycle
A module's lifecycle has four stages: build, load, run and remove. At each stage the kernel tracks module state.
On load, module_init is called; it prepares resources. On remove, module_exit is called; it cleans up. If the module is in use, rmmod is refused. The reference count is managed with try_module_get and module_put. Modules must match the running kernel; mismatch fails the load.
Practice Print module commands
Define void print_module_cmd(const char *cmd, const char *desc) with body printf("%s: %s\n", cmd, desc);. In main call it for four commands: ("insmod", "load"), ("rmmod", "unload"), ("lsmod", "list"), ("modprobe", "resolve").
Starter code
#include <stdio.h>
// Define print_module_cmd function
// Call it for insmod, rmmod, lsmod, modprobe
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_module_cmd(const char *cmd, const char *desc) {
printf("%s: %s\n", cmd, desc);
}
int main(void) {
print_module_cmd("insmod", "load");
print_module_cmd("rmmod", "unload");
print_module_cmd("lsmod", "list");
print_module_cmd("modprobe", "resolve");
return 0;
}Expected output
insmod: load rmmod: unload lsmod: list modprobe: resolve
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which command loads a module?
- modprobe -r
- rmmod
- insmod Correct answer
- lsmod
Explanation: insmod loads a .ko file into the kernel.
2 Print module name with printk
printk(KERN_INFO "Module %s loaded
", ____);
printk(KERN_INFO "Module %s loaded
", name);
Explanation: The name variable carries the module's name.
3 Match module commands
| Term | Meaning |
|---|---|
insmod |
Loads a module |
rmmod |
Removes a module |
lsmod |
Lists loaded modules |
modprobe |
Resolves dependencies |