1. 字符设备驱动模块加载与卸载函数模板
//设备结构体声明
struct xxx_dev_t
{
struct cdev cdev;
…….
}xxx_dev;
//设备驱动模块加载函数
static int __init xxx_init(void)
{
………
cdev_init(&xxx_dev.cdev, &xxx_fops); //初始化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); //注销设备
…………
}
2. 字符设备读、写、I/O控制函数
//读设备
static xxx_read(struct file * filp, char __user *buf, size_t count, loff_t * f_pos)
{
…………..
copy_to_user(buf,…………..);
……………….
}
//写设备
static xxx_write(struct file *filp, const char __user * buf,
size_t count, loff_t * f_pos)
{
…………..
copy_from_user(………..,buf,………..);
………………..
}
//ioctl函数
int xxx_ioctl(struct inode * inode , struct file *filp,
unsigned int cmd, unsigned long arg)
{
………..
switch(cmd){
case XXX_CMD:
………..
break;
………………
default:
……………
}
return 0;
}
struct file_operations xxx_fops =
{
.owner = THIS_MODULE,
.read = xxx_read,
.write = xxx_write,
.ioctl = xxx_ioctl,
………..
}