前面寫到如何向系統申請一個設備號,設備號就像我們的身份證號一樣,號本身并沒有什么特殊的意義,只有把這個號和人對應才有意義,通用設備號也需要和一個特殊的東西對于,這就是cdev, cdev是linux下抽象出來的一個用來描述一個字符設備的結構體,在linux下定義如下:
struct cdev {
struct kobject kobj;
struct module *owner;
const struct file_operations *ops;
struct list_head list;
dev_t dev;
unsigned int count;
};
結構體中有幾個成員事我們寫驅動的時候必須關心的:
dev 類型是dev_t,也就是我們的設備號
ops是一個同樣也是一個結構體并且是一個字符驅動實現的主體,字符驅動通常需要和應用程序交互,在學linux系統編程的時候,都會講到linux 應用程序通過系統調用陷入到內核空間,從而執行內核代碼,而驅動作為內核的一部分同樣也是需要在內核空間執行的,ops也就是file_operations這個結構體就是我們的驅動為應用程序調用驅動而實現的一個操作的集合,它的定義如下:
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
int (*readdir) (struct file *, void *, filldir_t);
unsigned int (*poll) (struct file *, struct poll_table_struct *);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
int (*aio_fsync) (struct kiocb *, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
int (*setlease)(struct file *, long, struct file_lock **);
long (*fallocate)(struct file *file, int mode, loff_t offset,loff_t len);
};
我們在驅動中要做的事情就是申請一個cdev并把cdev注冊到系統中去,操作cdev的函數有:
void cdev_init(struct cdev *, const struct file_operations *);
struct cdev *cdev_alloc(void);
int cdev_add(struct cdev *, dev_t, unsigned);
void cdev_del(struct cdev *);
1、cdev的定義
cdev的定義有兩種方式一種是:struct cdev cdev;另外一種是:strcut cdev cdev;cdev = cdev_alloc();
2、cdev的初始化
cdev_init實現cdev的初始化,主要的工作是將我們定義好的file_operaionts與cdev關聯起來,file_operations的實現根據實際需求來實現,后面詳細介紹。
3、cdev的注冊
cdev_add實現cdev的注冊,linux內核里維護了一個cdev_map的表,所謂cdev的注冊就是把我們的cdev注冊到cdev_map表上,cdev_map表結構如圖:

4、設備的刪除
cdev_del 將我們的cdev從cdev_map中移除。