world leader in high performance signal processing
Trace: » basic-char

A Basic Char Device Driver

The following code represents a most basic device driver. This code can be compiled to run on the host or the target systems. It is broken up into sections to help understand it.

Although this device driver does not have any actual Device Driver code it does perform the proper kernel functions to get to the point where the driver code can be added.

Includes and defines

/*
 * Basic Character mode driver
 */
 
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
 
#define SCMD_DEV "scmd_basic"
 
/* For static major number */
static int scmd_major = 250;
 
/* For dynamic major number */
static int scmd_major = 0;

The fops table

Here we fill the file operations table with NULLs so that the kernel knows that this character device driver is unable to handle any sort of file system request (like read/write/ioctl/etc…).

struct file_operations scmd_driver_fops = {
    NULL
};

Module registration

Here is the code that registers the module as a character device driver.

static int __init scmd_init(void)
{
    int ret;
 
    ret = register_chrdev(scmd_major, SCMD_DEV, &scmd_driver_fops);            
    if (ret < 0) {
        printk(KERN_NOTICE SCMD_DEV ": chrdev registration failed (ret=%i)\n", ret);
        return ret;
    }
 
    scmd_major = ret;
    printk(KERN_INFO SCMD_DEV ": register major %i\n", scmd_major);
 
    return 0;
}
module_init(scmd_init);

Here is the cleanup code to remove the character device driver.

static void __exit scmd_exit(void)
{
    unregister_chrdev(scmd_major, SCMD_DEV);
    printk(KERN_INFO SCMD_DEV ": unregistered char device\n");
}
module_exit(scmd_exit);