字符设备驱动程序的编写

来源:互联网 发布:淘宝详情页文字大小 编辑:程序博客网 时间:2024/05/16 14:35
字符设备是3类设备(字符设备、块设备、网络设备)中的一类,其驱动程序的完成的主要工作是初始化、添加和删除cdev结构体,申请和释放设备号。以及填充file_operations结构体中的操作函数,实现file_operations结构体中的read()、write和ioctl()等函数是驱动程序设计的主体工作。(参考宋宝华老师的书籍)cdev结构体   struct cdev{           struct kobject kobj;                //内嵌的kobject对象           struct module *owner;          //所属模块           struct file_operation *ops;    //文件操作结构体           struct list_head list;                         dev_t dev;                             //设备号           unsigned int count;};     1.dev_t dev 定义了设备号,位32位,12位主设备号,20位次设备    号      获取设备号:         MAJOR(dev_t dev);  //主设备号         MINOR(dev_t dev);  //此设备号    生成dev:        MKDEV(int major, int minor);    分配和释放设备号       //已知主设备       int register_chrdev_region(dev_t from, unsigned count, const char *name);       //避免设备号冲突       int alloc_chrdev_region(dev_t *dev, unsigned baseminor,unsigned count, const char *name);  2.操作cdev结构体的函数如下:      void cdev_init(struct cdev * , struct file_operations *);      struct cdev *cdev_alloc(void);      void cdev_put(struct cdev *p);      int cdev_add(struct cdev*, dev_t, unsigned);      void cdev_del(struct cdev*);     实现细节如下:    void cdev_init(struct cdev *cdev,struct file_operations *fops)    {      memset(cdev, 0 ,sizeof(*cdev));      INIT_LIST_HEAD(&cdev->list);      kobject_init(&cdev->kobj, &ktype_cdev_default);      cdev->ops = fops;//将传入的文件操作结构体指针赋值给cdev的ops   }       //动态申请一个cdev内存  struct cdev *cdev_alloc(){       struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);        if(p){            INIT_LIST_HEAD(&p->list);            kobject_init(&p->kobj, &ktype_cdev_dynamic);                }    return p;     

}

cdev_add()和cdev_del()分别向系统添加和删除一个cdevfile_operations结构体:   里面的函数比较多,主要是read()、write()、ioctl();
原创粉丝点击