Linux 字符设备驱动基本书写模板

来源:互联网 发布:淘宝箱子 编辑:程序博客网 时间:2024/05/18 01:41

1.设备结构体:

struct xxx_dev_t
{
    struct cdev cdev;
    ...   

}xxx_dev;

2.设备驱动模块加载函数:

static init _ _init xxx_init(void)

{

    ...
    
    cdev_init(&xxx_dev.cdev,&xxx_fpos);//初始化cdev
    
    xxx_dev.cdev-owner=THIS_MODULE;
    
    //获取字符设备号
    if(xxx_major)
    {
        register_chrdev_region(xxx_dev_no,1,DEV_NAME);
        
    }
    else
    {
        alloc_chrdev_region(&xxx_dev_no,0,1,DEV_NAME);
        
    }
    ret=cdev_add(&xxx_dev.cdev,xxx_dev_no,1);//注册设备

}

3.设备驱动模块卸载函数:

static void _ _exit xxx_exit(void)
{
    unregister_chrdev_region(xxx_dev_no,1);//释放占用的设备号
    cdev_del(&xxx_dev.cdev);//注销设备
    ...
 

}


4.字符设备驱动读,写,I/O控制函数模板:

//读设备
ssize_t xxx_read(struct file *filp,char _ _usr *buf,size_t count,loff_t *f_pos)
{
    ...
    copy_to_usr(buf,...,...);
    ...
}
//写设备
ssize_t xxx_write(struct file *filp,cnst char _ _usr *buf,size_t count,loof_t *f_pos)
{

...
copy_from_usr(..,buf,...);
...
}
//I/O控制函数
int xxx_ioctl(struct inode *inode,struct file *filp,usigned int cmd,unsigned long arg)
{

    ...
    switch(cmd)
    {
        ...
        case xxx_cmd1:
        ...
        break;
        default:
        return -ENOTTY;
    
    }
    return 0;
}

5.字符设备驱动文件操作结构体模板:

struct file_operations xxx_fops=

{

   .owner = THIS_MODULE,

   .read    = xxx_read,

   .write   = xxx_write,

   .ioctl    = xxx_ioctl,

   ...


};



原创粉丝点击