Devices¶
Minimal class, device, attr definition with exposure to sysfs
¶
To create a class, device, and an attribute for that device, you need to:
- Define the
class
anddevice
types. - Use
DEVICE_ATTR
and friends to define the attributes. - Within the
init
function:- Call the
create
functions.
- Call the
- Within the
exit
function:- Call the
exit
functions.
- Call the
// SPDX-License-Identifier: GPL-2.0
#include <linux/device.h>
#include <linux/module.h>
static ssize_t module_show(struct device *dev, struct device_attribute *attr, char *buf)
{
return sysfs_emit(buf, "%s\n", KBUILD_MODNAME);
}
static struct class *example_class;
static struct device *example_device;
static DEVICE_ATTR_RO(module);
static int __init example_init(void)
{
int ret;
example_class = class_create(THIS_MODULE, KBUILD_MODNAME);
example_device = device_create(example_class,
NULL,
0,
NULL,
KBUILD_MODNAME);
ret = device_create_file(example_device, &dev_attr_module);
return 0;
}
static void __exit example_exit(void)
{
device_remove_file(example_device, &dev_attr_module);
device_destroy(example_class, 0);
class_destroy(example_class);
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("");
MODULE_DESCRIPTION("");