3.字符设备创建class,自动创建设备
Posted 我爱一次性
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.字符设备创建class,自动创建设备相关的知识,希望对你有一定的参考价值。
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/device.h>
static dev_t fan_num;
static struct cdev fan_cdev;
static int status;
static struct class *fan_class;
static struct device *fan_device;
static int Odin_fan_open(struct inode *ip, struct file *fp)
printk("led_open status:%d\\n fan_num:%d",status,fan_num);
return 0;
static int Odin_fan_close(struct inode *ip, struct file *fp)
printk("led_close\\n");
return 0;
static struct file_operations fan_fops=
.owner = THIS_MODULE,
.open = Odin_fan_open,
.release = Odin_fan_close,
;
static int __init Odin_fan_init(void)
int ret;
status = 0;
ret = alloc_chrdev_region(&fan_num,0,1,"Odin_fan");
if(ret < 0)
printk("register_chrdev_region \\n");
goto dev_number_error;
printk("major:%d min:%d\\n",MAJOR(fan_num),MINOR(fan_num));
cdev_init(&fan_cdev,&fan_fops);
ret = cdev_add(&fan_cdev,fan_num,1);
//成功后 cat /proc/device/ -> 有显示Odin_fan的设备号
if(ret < 0)
printk("cdev_add \\n");
goto err_cdev_add;
fan_class = class_create(THIS_MODULE, "Odin_fan_class");
//创建完后 /sys/class/Odin_fan_class 就会出现
if(IS_ERR(fan_class))
ret = PTR_ERR(fan_class);
printk("fan class create fail \\n");
goto class_error;
fan_device = device_create(fan_class, NULL, fan_num, NULL, "odin_fan_device");
//创建完后 /dev/odin_fan_device 就会出现,不用再手动mknod设备节点了
if(IS_ERR(fan_device))
ret = PTR_ERR(fan_device);
printk("fan devices create fail \\n");
goto device_error;
return 0;
//和初始化的顺序相反
device_error:
device_destroy(fan_class, fan_num);
class_error:
class_destroy(fan_class);
err_cdev_add:
cdev_del(&fan_cdev);
dev_number_error:
unregister_chrdev_region(fan_num,1);
return ret;
static void __exit Odin_fan_exit(void)
device_destroy(fan_class, fan_num);
class_destroy(fan_class);
cdev_del(&fan_cdev);
unregister_chrdev_region(fan_num, 1);
printk("Odin_fan_ exit\\n");
module_init(Odin_fan_init);
module_exit(Odin_fan_exit);
MODULE_AUTHOR("oncethings");
MODULE_DESCRIPTION("Odin PI fan driver");
MODULE_LICENSE("GPL");
解析:
1.class_create
创建类,完成后 /sys/class/Odin_fan_class
2.device_create
再类创建完成后,在创建设备。通过这个函数不用再mknod设备节点了。每次开机都会自己创建好。 /dev/odin_fan_device
以上是关于3.字符设备创建class,自动创建设备的主要内容,如果未能解决你的问题,请参考以下文章
class_create(),device_create自动创建设备文件结点