字符设备驱动程序模版

2015-7-5 chenhui 设备驱动

#include <linux/module.h>        
#include <linux/types.h>          
#include <linux/fs.h>           
#include <linux/cdev.h>             

static int major = 0;
static int minor = 0;
struct cdev cdev;

static ssize_t xxx_read(struct file *filp, 
			char __user *buf, size_t count, loff_t *f_pos)
{
    printk("read\n");
}
static ssize_t xxx_write(struct file *filp, 
			char __user *buf, size_t count, loff_t *f_pos)
{
    printk("write\n");
}
static int xxx_open(struct inode *inode, struct file *filp)
{
    printk("open\n");
}

static struct file_operations fops =
{
    .owner    =THIS_MODULE,
    .read    =xxx_read,
    .write    =xxx_write,
    .open    =xxx_open
};

static int __init cdev_init(void)
{
    int rt;
    int count=1;
    dev_t dev;
    
    rt = alloc_chrdev_region(&dev, minor, count, "xxx");
    major = MAJOR(dev);

    if(rt < 0)
        printk(KERN_WARNING"Major Error!\n");

    dev = MKDEV(major, 0);
    cdev_init(&cdev, &fops);
    cdev.owner = THIS_MODULE;
    cdev.ops = &fops;

    rt = cdev_add(&cdev, dev, count);

    if(rt){

        printk(KERN_WARNING"Cdev Add Error!\n");
        cdev_del(&cdev);
        return -1;
    }
    return 0;
}

static void __exit cdev_exit(void)
{
    cdev_del(&cdev);
    unregister_chrdev_region(MKDEV (major, minor), 1);
}

module_init(cdev_init);
module_exit(cdev_exit);
MODULE_LICENSE("GPL");

发表评论:

Copyright ©2015-2016 freehui All rights reserved