All about programming in GNU/LINUX

Posts tagged “Major minor number

A simple Linux Driver : Allocating the Major Minor number

The first step in writing any Linux Device driver is to allocate a Major , Minor pair for the driver , this is a simple Linux Device Driver which allocates the Major , Minor pair and prints the same into DMESG


#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/types.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>

static dev_t first;

static int __init my_init(void) /*constructor*/
{
    int ret;

    printk(KERN_INFO "Drivre is being registered");
    if((ret = alloc_chrdev_region(&first,0,3,"Rao")) < 0) /*dynamic allocatin of Major , minor numbers*/
    {

        return ret;
    }
    printk(KERN_INFO "<MAJOR , MINOR ><%d %d>\n" , MAJOR(first),MINOR(first)); /*printing the Major , Minor pair into the dmesg*/
    return 0;
}

static void __exit my_exit(void) /*destructor function , executed when the driver is removed*/
{
    unregister_chrdev_region(first,3); 
    printk(KERN_INFO "dRIVER REMOVED");
}

    module_init(my_init);
    modue_exit(my_exit);
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("KARTHIC RAO");
    MODULE_DESCRIPTION("A SIMPLE DRIVER OF MINE");

here is the MAKEFILE for the driver

# If called directly from the command line, invoke the kernel build system.
ifeq ($(KERNELRELEASE),)

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

clean:
	$(MAKE) -C $(KERNEL_SOURCE) SUBDIRS=$(PWD) clean

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

	obj-m := simple_driver.o

endif