创建sys节点的例子:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/string.h>
#include <linux/device.h>
#include <linux/kdev_t.h>
static int hello_value;
static struct kobject *helloworld_kobj;
static struct class *hello_class;
//hello_china, virtual device
static ssize_t hello_show(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", hello_value);
}
static ssize_t hello_store(struct device *dev, struct device_attribte *attr, const char *buf, size_t count)
{
sscanf(buf,"%du", &hello_value);
return count;
}
static DEVICE_ATTR(helloChina, 0666, hello_show, hello_store);
//hello_value
static ssize_t hello_read(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", hello_value);
}
static ssize_t hello_write(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count)
{
sscanf(buf, "%du", &hello_value);
return count;
}
static const struct kobj_attribute hello_value_attribute = __ATTR(hello_value, 0777, hello_read, hello_write);
static int __init helloworld_init(void)
{
int retval;
struct device *temp;
dev_t hello_dev_t = MKDEV(350, 0);
hello_class = class_create(THIS_MODULE, "hello_class");
temp = device_create(hello_class, NULL, hello_dev_t, "%s", "hello_class");
retval = device_create_file(temp, &dev_attr_helloChina);
helloworld_kobj = kobject_create_and_add("helloword", kernel_kobj);
if(!helloworld_kobj)
return -ENOMEM;
retval = sysfs_create_file(helloworld_kobj, &(hello_value_attribute.attr));
if(retval)
kobject_put(helloworld_kobj);
return retval;
}
module_init(helloworld_init)
static void __exit helloworld_exit(void)
{
kobject_put(helloworld_kobj);
}
module_exit(helloworld_exit);
MODULE_DESCRIPTION("create hello_world and hello_value file node in /sys");
MODULE_AUTHOR("qyichao_ee@163.com");
MODULE_LICENSE("GPL");