首页 > 代码库 > 04 Linux字符设备驱动

04 Linux字符设备驱动

一、结构体

1. cdev 结构体

 1 struct cdev {
 2   struct kobject kobj; /* 内嵌的 kobject 对象 */
 3   struct module *owner; /*所属模块*/
 4   struct file_operations *ops; /*文件操作结构体*/
 5   struct list_head list;
 6   dev_t dev; /*设备号*/
 7   unsigned int count;
 8 };

2. file_operations 结构体

 1 struct file_operations {
 2   struct module *owner;
 3   /* 拥有该结构的模块的指针,一般为 THIS_MODULES */
 4   loff_t(*llseek)(struct file *, loff_t, int);
 5   /* 用来修改文件当前的读写位置 */
 6   ssize_t(*read)(struct file *, char _ _user *, size_t, loff_t*);
 7   /* 从设备中同步读取数据 */
 8   ssize_t(*write)(struct file *, const char _ _user *, size_t, loff_t*);
 9   /* 向设备发送数据*/
10   ssize_t(*aio_read)(struct kiocb *, char _ _user *, size_t, loff_t);
11   /* 初始化一个异步的读取操作*/
12   ssize_t(*aio_write)(struct kiocb *, const char _ _user *, size_t, loff_t);
13   /* 初始化一个异步的写入操作*/
14   int(*readdir)(struct file *, void *, filldir_t);
15   /* 仅用于读取目录,对于设备文件,该字段为 NULL */
16   unsigned int(*poll)(struct file *, struct poll_table_struct*);
17   /* 轮询函数,判断目前是否可以进行非阻塞的读取或写入*/
18   int(*ioctl)(struct inode *, struct file *, unsigned int, unsigned long);
19   /* 执行设备 I/O 控制命令*/
20   long(*unlocked_ioctl)(struct file *, unsigned int, unsigned long);
21   /* 不使用 BLK 的文件系统,将使用此种函数指针代替 ioctl */
22   long(*compat_ioctl)(struct file *, unsigned int, unsigned long);
23   /* 在 64 位系统上,32 位的 ioctl 调用,将使用此函数指针代替*/
24   int(*mmap)(struct file *, struct vm_area_struct*);
25   /* 用于请求将设备内存映射到进程地址空间*/
26   int(*open)(struct inode *, struct file*);
27   /* 打开 */
28   int(*flush)(struct file*);
29   int(*release)(struct inode *, struct file*);
30   /* 关闭*/
31   int (*fsync) (struct file *, struct dentry *, int datasync);
32   /* 刷新待处理的数据*/
33   int(*aio_fsync)(struct kiocb *, int datasync);
34   /* 异步 fsync */
35   int(*fasync)(int, struct file *, int);
36   /* 通知设备 FASYNC 标志发生变化*/
37   int(*lock)(struct file *, int, struct file_lock*);
38   ssize_t(*sendpage)(struct file *, struct page *, int, size_t, loff_t *, int);
39   /* 通常为 NULL */
40   unsigned long(*get_unmapped_area)(struct file *,unsigned long, unsigned long, unsigned long, unsigned long);
41   /* 在当前进程地址空间找到一个未映射的内存段 */
42   int(*check_flags)(int);
43   /* 允许模块检查传递给 fcntl(F_SETEL...)调用的标志 */
44   int(*dir_notify)(struct file *filp, unsigned long arg);
45   /* 对文件系统有效,驱动程序不必实现*/
46   int(*flock)(struct file *, int, struct file_lock*);
47   ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
48   /* 由 VFS 调用,将管道数据粘接到文件 */
49   ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); 
50   /* 由 VFS 调用,将文件数据粘接到管道 */
51   int (*setlease)(struct file *, long, struct file_lock **);
52 };

 

04 Linux字符设备驱动