Linux Kernel Module
Linux Kernel Module
Steps
1> Install and prepare module-assistant. 2> Create hello.c and the Makefile. 3> Compile the code. 4> Insert the compiled module into the running kernel. 5> Remove the module when youre finished.
1
$sudo apt-get install build-essential linux-headers$(uname -r) Or
2 [hello.c]
// Defining __KERNEL__ and MODULE allows us to access kernel-level code not usually available to userspace programs. #undef __KERNEL__ #define __KERNEL__ #undef MODULE #define MODULE // Linux Kernel/LKM headers: module.h is needed by all modules and kernel.h is needed for KERN_INFO. #include <linux/module.h> // included for all kernel modules #include <linux/kernel.h> // included for KERN_INFO #include <linux/init.h> // included for __init and __exit macros
static int __init hello_init(void) { printk(KERN_INFO "Hello world!\n"); return 0; // Non-zero return means that the module couldn't be loaded. }
static void __exit hello_cleanup(void) { printk(KERN_INFO "Cleaning up module.\n"); } module_init(hello_init); module_exit(hello_cleanup);
makefile
obj-m := hello.o KDIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd)
all: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean
3
$ make make -C /lib/modules/3.0.0-17-generic/build M=/var/www/lkm modules make[1]: Entering directory `/usr/src/linux-headers3.0.0-17-generic' CC [M] /var/www/lkm/hello.o Building modules, stage 2. MODPOST 1 modules CC /var/www/lkm/hello.mod.o LD [M] /var/www/lkm/hello.ko
4
///////////////////////////////////// $ sudo insmod hello.ko ///////////////////////////////////// $ tail /var/log/syslog <snip> Apr 20 16:27:39 laptop kernel: [19486.347191] Hello world! /////////////////////////////////////
5
$ sudo rmmod hello /////////////////////////////////
$ tail /var/log/syslog <snip> Apr 20 16:29:23 laptop kernel: [19486.347191] Cleaning up module.