Sunday 18 May 2014

Simple character driver code in linux

SIMPLE CHARACTER DRIVER

#include <linux/module.h>
#include <linux/fs.h>
#include <linux/major.h>
#include <linux/capability.h>
#include <asm/uaccess.h>

static ssize_t sample_char_read(struct file * file, char __user * buf,
                       size_t count, loff_t *ppos)
{
       printk("sample_char_read size(%ld)\n", count);
       return 0;
}

static ssize_t sample_char_write(struct file *filp, const char *buf,
                 size_t size, loff_t *offp)
{
       printk("sample_char_write size(%ld)\n", size);
       return size;

}

int sample_char_open(struct inode *inode, struct file *filp)
{
       printk("sample_char_open\n");
       return 0;
}

int sample_char_release(struct inode *inode, struct file *filp)
{

       printk("sample_char_release\n");
       return 0;
}

static struct file_operations sample_char_fops = {
      .read:          sample_char_read,
       .write:          sample_char_write,
       .open:          sample_char_open,
       .release:        sample_char_release,
};

int major_no;

int init_module(void)
{
       printk("\nLoading the sample char device driver\n");

       major_no = register_chrdev(0, "sample_char", &sample_char_fops);
       printk("major no = %d\n",major_no);
       return 0;
}

void cleanup_module(void)
{
       unregister_chrdev(major_no,"sample_char");
       printk("\nUnloading the sample char device driver\n");

}

MAKE FILE

obj-m +=char_1.o

all:
  make -C /lib/modules/$ (shell uname -r)/builds M=$(PWD) modules
clean: 
  make -C /lib/modules/$ (shell uname -r)/builds M=$(PWD) clean


It is driver file.if you want to check system call is working or not than make test file for it or use command from terminal.

No comments:

Post a Comment