Custom Search

Saturday, September 12, 2009

Create Sample Linux Kernel Module and insert it.

Tested in Debian Lenny
1) # apt-get install linux-headers

Select 'linux-headers-2.6.26-2-686' and install it ,based on kernel version of your system.
Use # uname -r to get kernel version.

# apt-get install linux-headers-2.6.26-2-686

2) Create hello.c kernel module file: vim hello.c

< linux/module.h >
< linux/kernel.h >

int init_module(void)
printk(KERN_INFO "init_module() called\n"); ----> this is printed in /var/log/messages when inserting or initializing kernel module hello.ko
return 0;

void cleanup_module(void)
printk(KERN_INFO "cleanup_module() called\n"); ----> this is printed in /var/log/messageswhen cleaning or removing kernel module hello.ko

3) Create a Makefile: vim Makefile
All you need to do is (edit) change Makefile to use current kernel build directory'/lib/modules/2.6.26-2-686/build/'.

obj-m += hello.o

make -C /lib/modules/2.6.26-2-686/build M=$(PWD) modules

make -C /lib/modules/2.6.26-2-686/build M=$(PWD) clean

Here $PWD return current working directory(where hello.c amd Make file are saved).Here files in the current working directory are compiled at current kernel directory '/lib/modules/2.6.26-2-686/build/' ,then clean it.

4) To build kernel module enter:
$ make

5) Run ls command to see newly build kernel module:
$ ls
hello.c hello.mod.c hello.o modules.order
hello.ko hello.mod.o Makefile Module.symvers

6) Here hello.ko is kernel module file. To see information about module, enter:
$ modinfo hello.ko 

7) To load kernel module, enter:
$ insmod hello.ko
$ modprobe hello

8) To list installed Linux kernel module, enter:
$ lsmod
$ lsmod | grep hello

9) To remove hello Linux kernel module, enter:
$ rmmod hello

10) This module just logs message to a log file called /var/log/messages (/var/log/syslog), enter:
$ tail -f /var/log/messages

No comments:

Post a Comment