Linux 设备创建 device_create() 和 device_create_file()

1、device_create 

如果成功,它将会在 /dev 目录下产生 /dev/mdev 设备

2. device_create_file

使用这个函数时要引用 device_create 所返回的 device* 指针,作用是在 /sys/class/ 下创建一个属性文件,从而通过对这个属性文件进行读写就能完成对应的数据操作。

/**
 * device_create - creates a device and registers it with sysfs
 * @class: pointer to the struct class that this device should be registered to
 * @parent: pointer to the parent struct device of this new device, if any
 * @devt: the dev_t for the char device to be added
 * @drvdata: the data to be added to the device for callbacks
 * @fmt: string for the device's name
 *
 * This function can be used by char device classes.  A struct device
 * will be created in sysfs, registered to the specified class.
 *
 * A "dev" file will be created, showing the dev_t for the device, if
 * the dev_t is not 0,0.
 * If a pointer to a parent struct device is passed in, the newly created
 * struct device will be a child of that device in sysfs.
 * The pointer to the struct device will be returned from the call.
 * Any further sysfs files that might be required can be created using this
 * pointer.
 *
 * Returns &struct device pointer on success, or ERR_PTR() on error.
 *
 * Note: the struct class passed to this function must have previously
 * been created with a call to class_create().
 */
struct device *device_create(struct class *class, struct device *parent,
			     dev_t devt, void *drvdata, const char *fmt, ...)



/**
 * device_create_file - create sysfs attribute file for device.
 * @dev: device.
 * @attr: device attribute descriptor.
 */
int device_create_file(struct device *dev,
		       const struct device_attribute *attr)



/*********************** 代码例子 *****************************/
struct mydev {
    const char *name;
    struct device *dev;
    int id;
    int index;
};

struct class mdev_class = class_create(THIS_HODULE, "mydevice"); // 创建class
struct mydev *mdev;


int mdev_register(struct mdev *sdev)
{
	int ret;
	sdev->index = atomic_inc_return(&device_count);
	sdev->dev = device_create(mdev_class , NULL, MKDEV(0, sdev->index), NULL, sdev->name);
	if (IS_ERR(sdev->dev))
		return PTR_ERR(sdev->dev);
	ret = device_create_file(sdev->dev, &dev_attr_id);
	if (ret < 0)
		goto err_create_file_1;
	ret = device_create_file(sdev->dev, &dev_attr_name);
	if (ret < 0)
		goto err_create_file_2;
	dev_set_drvdata(sdev->dev, sdev);
	sdev->id = 0;
	return 0;

err_create_file_2:
	device_remove_file(sdev->dev, &dev_attr_id);
	return ret;

err_create_file_1:
	device_destroy(criticallog_class, MKDEV(0, sdev->index));

	return ret;
}
EXPORT_SYMBOL_GPL(mdev_register);

 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值