Friday 9 January 2015

Writing a simple Linux Device Driver

          A device driver is a program that controls a particular type of device that is attached to your computer. There are device drivers for printers, displays, CD-ROM readers, diskette drives, and so on.
Now let us write a simple Hello World driver code.
Create a directory anywhere in your home folder and navigate into that directory.
mkdir hello
cd hello
Create two files hello.c and Makefile
You can use any editor as you wish. Here I use Kate.
kate hello.c
Type the following code

#include <linux/init.h>
#include <linux/module.h>
static int __init hello_init (void) {
printk(KERN_ALERT "Hello World!!!");
return 0;
}
static int __exit hello_exit(void) {
printk(KERN_ALERT "Goodbye World!!!");
return 0;
}
module_init(hello_init);
module_exit(hello_exit);

Here, the hello_init() function runs when the module is loaded and hello_exit() funtion runs when the module is unloaded. Save the code.
Next we can create the Makefile.
kate Makefile
Type the follwing code in it. Make sure that you intent the code perfectly.


ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
    rm -rf *.o *.ko *.mod.*
endif


When you are done till here, we need to build the module. For that type,
make
It hardly takes half a minute. When the module is successflly built, you get a bunch of object files in the hello directory. Thus the Hello World module is ready.
Now let's see the working of the module by loading it into the kernel. Type,
sudo insmod hello.ko
This will load the module into the kernel which we can check by typing ,
lsmod
You get a list of module on top you get your hello module. To see whether the module is running in you kernel or not, type
dmesg
The Hello World message will be printed that we wrote in hello.c file
To remove the module type the following instruction in the terminal
sudo rmmod hello
Here the exit function that we typed in hello.c is run. To check the output type,
dmesg