//linux 字符设备驱动的组成模板
struct xxx_dev_t{
struct cdev cdev;
…
};
/*设备驱动模块加载函数*/
static int __init xxx_init(void)
{
...
cdev_init(&xxx_dev.cdev, &xxx_fpos); /*初始化cdev*/
xxx_dev.cdev.owner = THIS_MODULE;
/*获取字符设备号*/
if(xxx_major){
register_chrdev_region(xxx_dev_no,1,DEV_NAME);
} else {
alloc_chrdev_region(&xxx_dev_no,0,1,DEV_NAME);
}
ret = cdev_add(&xxx_dev.cdev, xxx_dev_no, 1); /*注册设备*/
...
}
/*设备驱动模块卸载模块*/
static void __exit xxx_exit(void)
{
unregister_chrdev_region(xxx_dev_no, 1); /*释放占用的设备号*/
cdev_del(&xxx_dev.cdev); /*注销设备*/
...
}
3. file_operations定义了字符设备驱动提供给虚拟文件系统的接口函数,常见的字符设备驱动的这三个函数的形式如下:
//读设备
ssize_t xxx_read(struct file *filp ,char __ user *buf, size_t count, loff_t *f_ops)
{
...
copy_to_user(buf, ..., ...);
...
}
//写设备
ssize_t xxx_write(struct file *filp , const char __user *buf , size_t count, loff_t *f_ops)
{
…
copy_from_user(…, buf, …);
…
}
//ioctl 函数
long xxx_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
…
switch(cmd){
case xxx_CMD1:
...;
break;
...
default ://不支持的命令
return -ENOTTY;
}
return 0;
}