How to create Linux kernel modules

J

Jeraldson

Guest
hey birds am very concerned when it comes to programming kernel modules... i just started yesterday and as it always goes i tried to program a module that says "Hello World" but while running my codes the module could not be installed. i need help.....these are the codes i wrote.......

/*
* hello−1.c − The simplest kernel module.
*/
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
int init_module(void)
{
printk(KERN_INFO "Hello world 1.\n");
/*
* A non 0 return means init_module failed; module can't be loaded.
*/
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye world 1.\n");
}
 


The code you have posted looks OK. Your average "hello world" kernel module.
How are you building your .ko file?

If you use a Makefile like this:
Code:
obj-m += hello-1.o
all:
    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
That should allow you to build your module for the currently running kernel using make - Assuming that your C file is called hello-1.c as listed in your posted code that is. If your C file is called something else then you should change hello-1.o in the makefile to {yourCFileName}.o

After a successful run of make, you should see the .ko object in the source directory for your module.
To load your module into the kernel, use the following:
Code:
sudo insmod ./hello-1.ko
Alternatively you could use the modprobe command, which will load and start any other modules that your module depends on. But the example module you have posted doesn't really have any dependencies, so insmod will suffice!

To unload/remove it from the kernel use the following:
Code:
sudo rmmod hello-1.ko

To see whether your module loaded and unloaded sucessfully, use the dmesg command to view the kernel logs:
Code:
dmesg | tail
All being well, the "Hello/goodbye world" text you used in your printk statements should be listed in the log output.
 
Last edited:


Top