总线属性使用struct bus_attribute来描述,Linux给我们提供了一个宏,可以用来定义一个总线属性,那就是BUS_ATTR宏,该宏定义如下:
#define BUS_ATTR(_name, _mode, _show, _store) \
struct bus_attribute bus_attr_##_name = __ATTR(_name, _mode, _show, _store)
其中_name为属性的名字,_mode为属性文件访问权限,_show和_store是两个方法,用于显示和存储一些信息。创建总线属性文件使用bus_create_file,原型如下:
int bus_create_file(struct bus_type *, struct bus_attribute *);
删除总线属性文件使用bus_remove_file函数,原型如下:
void bus_remove_file(struct bus_type *, struct bus_attribute *);
ldd上的一个例子:
static char *Version = "$Revision: 1.9 $";
...
/*
* Export a simple attribute.
*/
static ssize_t show_bus_version(struct bus_type *bus, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", Version);
}
static BUS_ATTR(version, S_IRUGO, show_bus_version, NULL);
static int __init ldd_bus_init(void)
{
...
if (bus_create_file(&ldd_bus_type, &bus_attr_version))
printk(KERN_NOTICE "Unable to create version attribute\n");
...
}
二、设备属性
设备属性使用struct device_attribute来描述,定义设备属性也有一个宏DEVICE_ATTR,该宏定义如下:
#define DEVICE_ATTR(_name, _mode, _show, _store) \
struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store)
宏参数同总线属性的宏参数含义一样,创建设备属性文件使用device_create_file函数,原型如下:
int device_create_file(struct device *device, const struct device_attribute *entry);
删除设备属性文件使用函数device_remove_file函数,原型如下:
void device_remove_file(struct device *dev, const struct device_attribute *attr);
三、驱动属性
驱动属性使用struct driver_attribute来描述,定义驱动属性也可以使用宏DRIVER_ATTR来完成,该宏定义如下:
#define DRIVER_ATTR(_name, _mode, _show, _store) \
struct driver_attribute driver_attr_##_name = \
__ATTR(_name, _mode, _show, _store)
创建驱动属性文件使用函数driver_create_file,原型如下:
int driver_create_file(struct device_driver *driver, const struct driver_attribute *attr);
删除驱动属性文件使用函数driver_remove_file,原型如下:
void driver_remove_file(struct device_driver *driver, const struct driver_attribute *attr);
总结,不管是总线、还是设备或者是驱动的属性文件最终都是调用的sysfs_create_file函数去创建的,删除属性文件都是通过调用sysfs_remove_file去完成的,最终建立了sysfs这样一个基于ram的虚拟文件系统。