The sysfs allow User space kernel space simple communication .
The code
#include <linux/kobject.h>#include <linux/string.h>#include <linux/sysfs.h>#include <linux/module.h>#include <linux/init.h>/** The module demonstrats creating 2 attributes in a subdirectory of sysfs.* ls the /sys/kernel/mykobject*/static int intValue = 0;static char TxtBuffer[50];static ssize_t attr_show(struct kobject *kobj, struct kobj_attribute *attr,char *buf){if (strcmp(attr->attr.name, "TxtBuffer") == 0){return sprintf(buf, "%s\n", TxtBuffer);}if (strcmp(attr->attr.name, "intValue") == 0){return sprintf(buf, "%d\n", intValue);}return 0;}static ssize_t attr_store(struct kobject *kobj, struct kobj_attribute *attr,const char *buf, size_t count){if (strcmp(attr->attr.name, "TxtBuffer") == 0){strcpy (TxtBuffer, buf);return count;}if (strcmp(attr->attr.name, "intValue") == 0){int theTmpVar;sscanf(buf, "%du", &theTmpVar);intValue = theTmpVar;return count;}return 0;}static struct kobj_attribute intValue_attribute =__ATTR(intValue, 0666, attr_show, attr_store);static struct kobj_attribute TxtBuffer_attribute =__ATTR(TxtBuffer, 0666, attr_show, attr_store);static struct attribute *attrs[] = {&intValue_attribute.attr,&TxtBuffer_attribute.attr,NULL,};static struct attribute_group attr_group = {.attrs = attrs,.name = NULL, /* we want them in the same directory */};static struct kobject *mykobject;static int mykobject_init(void){int retval;mykobject = kobject_create_and_add("mykobject", kernel_kobj);if (!mykobject)return -ENOMEM;retval = sysfs_create_group(mykobject, &attr_group);if (retval)kobject_put(mykobject);return retval;}static void mykobject_exit(void){kobject_put(mykobject);}module_init(mykobject_init);module_exit(mykobject_exit);MODULE_LICENSE("GPL");MODULE_AUTHOR("Zvika Peer <zvikapeer@hotmail.com>");
After installing the module using insmod let test it. The module directory is :
ls /sys/kernel/
Inspecting the mykobject attributes
zvika@zvika-Linux:~/Learn/Drivers/HelloWorld$ ls /sys/kernel/mykobject
intValue TxtBuffer
Inserting Data into the attributes:
zvika@zvika-Linux:~/Learn/Drivers/HelloWorld$ sudo echo "Hello zvika" > /sys/kernel/mykobject/TxtBuffer
zvika@zvika-Linux:~/Learn/Drivers/HelloWorld$ sudo echo 164 > /sys/kernel/mykobject/intValue
Retrieving the data back from the attributes:
zvika@zvika-Linux:~/Learn/Drivers/HelloWorld$ sudo cat /sys/kernel/mykobject/intValue
164
zvika@zvika-Linux:~/Learn/Drivers/HelloWorld$ sudo cat /sys/kernel/mykobject/TxtBuffer
Hello zvika
אין תגובות:
הוסף רשומת תגובה