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;

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.

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

When you are done till here, we need to build the module. For that type,
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 ,
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
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,

No comments:

Post a Comment