All about programming in GNU/LINUX


Linux Device Drivers-2:My first driver

The headers used to write a Device driver code or a kernel program are not found in /usr/include , they are found in /usr/src/linux-headers-$(uname -r)

Here is a small Device driver code which registers itself .When A device driver is registered using alloc_chrdev_region() , its entry is made in the file /proc/devices with the name mentioned in the same function call .The messages printed using printk() function will not appear on standard output , instead the message can be viewed in the last few lines of dmesg command.

dev_t devno;
/*first 12 Bits of this 32-bit data type is used to store the MAJOR number of the device and i
  remaining 20 bits for the minor number*/
static int __init constructor(void)/*initialization function,this runs when the module is loaded on top of kernel*/
 int ret;

 if((ret=alloc_chrdev_region(&devno,0,3,”RAO’s DRIVER”))<0) /*Used to dynamically allocate the major number for the device ,defined in <linux/fs.h>,The device is       
                                                             registered and A device by name “RAO’s DRIVER ” will be seen inside the file /proc/devices*/        
  return ret;
 printk(KERN_INFO “\nMajor NO=%d,MINOR NUMBER=%d\n”,MAJOR(devno),MINOR(devno));/*Kernel’s equivalent of printf,the output can be viewed by using dmesg command*/
 return 0;

static void __exit destructor(void)/*Kernel automatically loads this function when the module removed from top of kernel*/

 unregister_chrdev_region(devno,3); /*To unregister the registered device */
 printk(KERN_INFO “\nRAO’s module removed”);

module_init(constructor);/*Tells the kernel the name of the function to be called when the module is loaded*/
module_exit(destructor);/*Tells the kernel the name of the function to be called when the module is removed*/

/*More information about hte code is given to the kernel using MODULE_ macros*/


The source code of the Makefile

# If called directly from the command line, invoke the kernel build system.

    KERNEL_SOURCE := /usr/src/linux-headers-$(shell uname -r)
    PWD := $(shell pwd)
    $(MAKE) -C $(KERNEL_SOURCE) SUBDIRS=$(PWD) modules


# Otherwise KERNELRELEASE is defined; we’ve been invoked from the
# kernel build system and can use its language.

    obj-m := test.o



Steps to compile and run the code:Name the source code as test.c and place the Makefile in the same directory.The steps are depicted in the image below



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s