Archive for the ‘C’ Category

“Hello world” kernel module

Make a directory called “helloM” in your home dir and edit the following .C file, called “hello.c”:

/*hello.c – The simplest kernel module.*/

#include <linux/module.h>  /* Needed by all modules */
#include <linux/kernel.h>  /* Needed for KERN_ALERT */


int init_module(void)
{
printk("<1>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_ALERT "Goodbye world 1.\n");
}

To compile this kernel module you need to edit the following “Makefile” (called “Makefile” !):

ifneq ($(KERNELRELEASE),)

# We were called by kbuild

obj-m += hello.o

else  # We were called from command line

KDIR := /lib/modules/$(shell uname -r)/build

#KDIR := /home/cynove/src/kernel/linux-source-2.6.31

PWD  := $(shell pwd)

default:

@echo '    Building target module 2.6 kernel.'

@echo '    PLEASE IGNORE THE "Overriding SUBDIRS" WARNING'+

$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

install:

./do_install.sh *.ko

endif  # End kbuild check

######################### Version independent targets ##########################

clean:

rm -f -r *.o *.ko .*cmd .tmp* core *.i

Then, within our working folder, type make, which will process the Makefile and create a module file, hello.ko.

To install the module,type:

sudo insmod hello.ko

To verify the module has output to the log file in Ubuntu 11.10 type:

 tail /var/log/kern.log
 

You should read the message of the init_module() method, that is “Hello world 1.”

To remove the module, type:

sudo rmmod hello.ko

In the tail of the kern.log you should find “Goodbye world 1.”.

Funny! By these first steps you can make interesting kernel modules!

Categories
Links: