1. 定义一个结构体file_operations
static struct file_operations first_drv_fops = {
.owner = THIS_MODULE,
.open = first_drv_open,
.write = first_drv_write,
};
2.结构体中函数实现
static int first_drv_open(struct inode *inode, struct file *file)
{
printk("first_drv_open\n");
return 0;
}
static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
printk("first_drv_write\n");
return 0;
}
3.实现入口函数
static int first_drv_init(void)
{
/* 在内核中注册结构体 */
major=register_chrdev(0, "first_drv", &first_drv_fops);
/* 创建类 */
firstdrv_class = class_create(THIS_MODULE, "firstdrv");/* 在sys目录下创建led设备类目录 */
/* 在类下创建设备 */
firstdrv_class_dev = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */
return 0;
}
4.出口函数
static void first_drv_exit(void)
{
unregister_chrdev(major, "first_drv");
class_device_unregister(firstdrv_class_dev);
class_destroy(firstdrv_class);
}
5.修饰入口函数
module_init(first_drv_init);
6.修饰出口函数
module_exit(first_drv_exit);