第一步:了解一个重要的数据结构
struct file_operation
{
ssize_t (*read)(......);
ssize_t(*write)(......);
int (*ioctl)(..........);
int (*open)(.......);
int (*release)(.......);
//..............
}
结构体file_operation是设备驱动程序的接口,它定义在include/linux/fs.h.
第二步:设备注册
驱动程序模块通过函数register_chrdev来完成内核的注册。该函数为:
int register_chrdev(unsigned int major,const char *name,struct file_operation *fops);
//major为主设备号,name为设备名,fops为结构体
第三步:设备卸载
驱动程序模块通过unregister_chrdev函数来完成设备的卸载。该函数:
int unregister_chrdev(unsigned int major,const char *name);
第四步:打开/释放设备
int open(const char *pathname,int flags);
static int release(struct inode *inode,struct filp*filp);
注:*inode和*filp相当于fd(文件描述符)
第五步:读写设备
ssize_t read(............);
ssize_t write(...........);
unsigned long copy_to_user(void *to,const void *from,unsigned long count);
unsigned long copy_from_user(......);
第六步:读写以外的I/O操作
int (*iotcl)(struct innode*inode,struct file*filp,unsigned int cmd,unsigned long arg);//cmd是用户空间传递到驱动程序的命令,arg附加命令的参数