//1、字符设备驱动模块加载与卸载函数
//设备结构
struct XXX_dev
{
struct cdev cdev; /*cdev结构体*/
...
}XXX_dev ;
/*设备驱动模块加载函数*/
static int __int XXX_init(void)
{
...
cdev_init(&XXX_dev.cdev, &XXX_fops); //初始化cdev
/* 申请设备号*/
if (XXX_major)
result = register_chrdev_region(XXX_dev_no, 1, DEV_NAME);
else /* 动态申请设备号 */
{
result = alloc_chrdev_region(&XXX_dev_no, 0, 1, DEV_NAME);
globalmem_major = MAJOR(devno);
}
ret = cdev_add(&dev->cdev, devno, 1);
...
}
/*模块卸载函数*/
static void __exit XXX_exit(void)
{
unregister_chrdev_region(XXX_dev_no, 1); /*释放设备号*/
cdev_del(&XXX_devp.cdev); /*注销cdev*/
...
}
//文件设备驱动的file_operations结构体中成员函数
/*读函数*/
static ssize_t XXX_read(struct file *filp, char __user *buf, size_t count,
loff_t *ppos)
{
...
/*内核空间->用户空间*/
copy_to_user(buf, ..., ...)
...
}
/*写函数*/
static ssize_t globalmem_write(struct file *filp, const char __user *buf,
size_t count, loff_t *ppos)
{
...
/*用户空间->内核空间*/
copy_from_user(..., buf, ...)
...
}
/* ioctl设备控制函数 */
static int globalmem_ioctl(struct inode *inodep, struct file *filp, unsigned
int cmd, unsigned long arg)
{
...
switch (cmd)
{
case XXX_CMD1:
...
break;
...
default:
return - ENOTTY;
}
return 0;
}
//字符设备驱动文件操作结构体模板
/*文件操作结构体*/
static const struct file_operations globalmem_fops =
{
.owner = THIS_MODULE,
.read = XXX_read,
.write = XXX_write,
.ioctl = XXX_ioctl,
...
};
文章评论(0条评论)
登录后参与讨论