| Linux: 'Hello World' Kernel Module |
| Monday, 26 September 2011 05:33 |
|
Here's a 'Hello World' Linux kernel module example. The C code here is derived from 'The Linux Documentation Project' www site, which also contains more details about getting started writing your own modules. Note: I still need to read up on what exactly a 'tainted' kernel is. LinuxKernelModuleExample.c
#include <linux/module.h>
#include <linux/kernel.h>
/* If MODULE_LICENSE is not specified you will see
* messages like the below in '/var/log/messages':
*
* Sep 25 21:35:59 hostname kernel: [722119.034840] Disabling lock debugging due to kernel taint
* Sep 25 21:35:59 hostname kernel: [722119.034844] LinuxKernelModuleExample: module license 'unspecified' taints kernel.
*/
MODULE_LICENSE("gpl");
int init_module(void) {
/* Log message with log level 'KERN_INFO'.
* Message will display in '/var/log/messages'
*/
printk(KERN_INFO "init_module\n");
return 0;
}
void cleanup_module(void) {
/* Log message with log level 'KERN_INFO'.
* Message will display in '/var/log/messages'
*/
printk(KERN_INFO "cleanup_module\n");
}
Makefile
obj-m += LinuxKernelModuleExample.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean # #Need to run all of the below as root # info: modinfo LinuxKernelModuleExample.ko # # Copy the new module to /lib/modules/`uname -r` because # modprobe looks for modules by default here. # # Also modprobe expects that modules.dep exists in this folder as well. # install: cp ./LinuxKernelModuleExample.ko /lib/modules/`uname -r` depmod /lib/modules/`uname -r`/LinuxKernelModuleExample.ko modprobe -a LinuxKernelModuleExample # # See if the kernel module is installed, amd dump the tail of the log # lsmod: ls | grep LinuxKernelModuleExample tail /var/log/messages # # Remove the kernel module # remove: modprobe -r LinuxKernelModuleExample rm -f /lib/modules/`uname -r`/LinuxKernelModuleExample.ko ls /lib/modules/`uname -r` # # Test the module # test: install lsmod remove |