Thursday, November 8, 2012

Linux "hello world" Kernel Module

Here is a "hello world" program which loads and unloads a kernel module


#undef __KERNEL__
#define __KERNEL__

#undef MODULE
#define MODULE

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/unistd.h>
#include <asm/fcntl.h>
#include <asm/errno.h>
#include <linux/types.h>
#include <linux/dirent.h>
#include <linux/string.h>
#include <linux/fs.h>

static int __init hello_init(void) {
   printk(KERN_INFO "Hello World\n");
   return 0;

static void __exit hello_cleanup(void) {
   printk(KERN_INFO "Cleaning up modules\n");



obj-m := hello.o
KVERSION := $(shell uname -r)
KDIR := /lib/modules/$(shell uname -r)/build/
PWD := $(shell pwd)
INC := -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/

 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) modules

 $(MAKE) $(INC) -C $(KDIR) M=$(PWD) clean

Run "make" , Output:

[root@localhost kernel-programs]# make

make -I/usr/src/kernels/2.6.18-194.el5-x86_64/include/ -I/usr/include -I/usr/lib/x86_64-redhat-linux4E/include/ -C /lib/modules/2.6.18-194.el5/build/ M=/root/kernel-programs modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-194.el5-x86_64'
  CC [M]  /root/kernel-programs/hello.o
  Building modules, stage 2.
  CC      /root/kernel-programs/hello.mod.o
  LD [M]  /root/kernel-programs/hello.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-194.el5-x86_64'

[root@localhost kernel-programs]# 


[root@localhost kernel-programs]# ls -l
total 340
-rw-r--r-- 1 root root    548 Nov  8 11:59 hello.c
-rw-r--r-- 1 root root 159367 Nov  8 12:14 hello.ko
-rw-r--r-- 1 root root    660 Nov  8 12:14 hello.mod.c
-rw-r--r-- 1 root root  80528 Nov  8 12:14 hello.mod.o
-rw-r--r-- 1 root root  80128 Nov  8 12:14 hello.o
-rw-r--r-- 1 root root    327 Nov  8 11:55 Makefile
-rw-r--r-- 1 root root      0 Nov  8 11:59 Module.markers
-rw-r--r-- 1 root root      0 Nov  8 11:59 Module.symvers

[root@localhost kernel-programs]# 

Load the "hello.ko" module

[root@localhost kernel-programs]# insmod hello.ko

Verify: "tail -f /var/log/messages"

Nov  8 12:17:04 localhost kernel: Hello World

Unload the module: "rmmod hello"

Nov  8 12:18:32 localhost kernel: Cleaning up modules

1 comment :

  1. The Bluetooth modules provide a platform to quickly and safely go into production with competitive and advanced features.