Thursday 20 March 2014

Create a Simple Kernel Module on Ubuntu

Create a file, hello.c, that prints "Hello, world" when the module is loaded and prints "Goodbye, cruel world" when the module is unloaded
#include 
#include 
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) {
        printk(KERN_ALERT "Hello, world\n");
        return 0;
}

static void hello_exit(void) {
        printk(KERN_ALERT "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Create a Makefile
ifneq ($(KERNELRELEASE),)
        obj-m := hello.o

else
        KERNELDIR ?= /lib/modules/$(shell uname -r)/build
        PWD := $(shell pwd)

default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

Running make will create the kernel module named hello.ko
make

load the module by using the following command
sudo insmod hello.ko
View the messages by entering the dmesg command.
dmesg

unload the module by using the following command
sudo rmmod hello

No comments:

Post a Comment