#include <linux/init.h>
#include <linux/module.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/string.h>
static int hello_value;
Static ssize_t hello_show (struct kobject *kobj, struct kobj_attribute *attr, char *buf)
{
Return sprintf (buf, "%d\n", Hello_value);
}
Static ssize_t Hello_store (struct kobject *kobj, struct kobj_attribute *attr, const char *BUF, size_t count)
{
SSCANF (buf, "%du", &hello_value);
return count;
}
static struct Kobj_attribute Hello_value_attribute = __attr (Hello_value, 0666, Hello_show, Hello_store);
static struct Kobject *hellowold_kobj;
static int __init helloworld_init (void)
{
int retval;
Helloworld_kobj = Kobject_create_and_add ("HelloWorld", kernel_kobj);
if (!helloworld_kobj)
Return-enomem;
retval = Sysfs_create_file (Helloworld_kobj, &hello_value_attribute);
if (retval)
Kobject_put (Helloworld_kobj);
return retval;
}
static void __exit helloworld_exit (void)
{
Kobject_put (Helloworld_kobj);
}
Module_init (Helloworld_init);
Module_exit (Helloworld_exit);
Module_license ("GPL");
Module_auther (doublenian.xie@gmail.com);
First, the results of the operation:
root@thiz:/sys/kernel/hellowrold# ls
Hello_value
root@thiz:/sys/kernel/helloworld# echo 1 > Hello_value
root@thiz:/sys/kernel/hellowrold# Cat Hello_value
1
Second, analysis
1, directory items (/sys/kernel/helloworld): Through the function kobject_create_and_add ("HelloWorld", kernel_kobj) can be in/sys/ Create a HelloWorld directory entry under kernel.
2. Property file (Hello_value): Established by Function Sysfs_create_file (Helloworld_kobj, &hello_value_attribute). This also establishes the connection and correspondence between the file and the operation.
3, Operation (Hello_show, Hello_store): In the SYS system, the operation of the file has 2 functions, one is show, one is the store, these two functions and ordinary files of the read and write functions somewhat similar, is their thin version. For sprintf and sscanf is the encapsulation of the Copy_from_user and Copy_to_user functions .
4, if a set of properties can be as follows:
static struct attribute *attrs [] = {
&foo_attribute.attr,
&baz_attribuet.attr,
&bar_attribute.attr,
NULL,/* need to NULL terminate the list of attributes * *
};
static struct Attribute_group Attr_group = {
. Attrs = Attrs,
};
retval = Sysfs_create_group (Example_kobj, &attr_group);