字符设备驱动--- 数据结构 设备注册struct cdev , 注销

来源:互联网 发布:数控编程用什么格式 编辑:程序博客网 时间:2024/06/06 19:49

三种重要的数据结构 struct  file - struct  inode -  struct  file_operations:

  在Linux 字符设备驱动程序中,有 3 种重要的 数据结构 .

            1,struct  file.

            2,struct  inode.

            3,struct  file_operations

(1)  struct  file

            代表一个打开的文件,系统中每打开的文件在内核空间都有一个关联的 struct  file ,

            它由内核在打开文件时创建关闭文件后释放.

            重要成员: loff_t  f_pos  //文件读写位置.

                              struct  file_operations  * f_op  .

(2)  struct  inode

            用来记录文件的物理上的信息,因此,它和代表打开文件的  file  结构是不同的,

            一个文件可以对应多个 struct  file 结构,但只有一个 struct  inode 结果.

            重要成员: dev_t   i_rdev  //设备号.

(3)  struct  file_operations

            一个函数指针的集合,定义能在设备上进行的操作,结构中的成员指向驱动中的函数

            这些函数实现一个特别的操作,对应不支持的操作保留为 NULL.

            eg:    struct  file_operations  mem_fops = {

                                                            .owner = THIS_MODULE,

                                                            .llseek = mem_seek,

                                                            .read    = mem_read,

                                                            .write    = mem_write,

                                                            .open   = mem_open,

                                                            ................ 

                                                            };

设备注册  struct  cdev 

            在 Linux 2.6 内核中,字符设备使用  struct  cdev 来描述.

            字符设备的注册可分为如下 3 个步骤

                        1,分配 cdev.

                        2,初始化 cdev.

                        3,添加 cdev.

(1)  分配 cdev_alloc 

                        使用 cdev_alloc 函数完成,struct  cdev * cdev_alloc(void).

(2)  初始化 cdev_init

                        void  cdev_init( struct cdev* cdev  ,  const struct file_operations * fops).

                                               待初始化的 cdev 结构       设备对应的操作函数集

(3)  设备注册(添加) cdev_add

                        int  cdev_add(       struct cdev *p ,                   dev_t  dev ,                    unsigned  count ).

                                           待添加到内核的字符设备结构           设备号                        添加的设备个数


设备注销 cdev_del :

            字符设备的注销使用 cdev_del 函数来完成.

            int  cdev_del ( struct  cdev *p )

                        参数:  p 为要注销的字符设备结构.