sysfs.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* https://github.com/cirosantilli/linux-kernel-module-cheat#sysfs */
  2. #include <linux/init.h>
  3. #include <linux/kobject.h>
  4. #include <linux/module.h>
  5. #include <linux/stat.h>
  6. #include <linux/string.h>
  7. #include <linux/sysfs.h>
  8. #include <uapi/linux/stat.h> /* S_IRUSR, S_IWUSR */
  9. enum { FOO_SIZE_MAX = 4 };
  10. static int foo_size;
  11. static char foo_tmp[FOO_SIZE_MAX];
  12. static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
  13. char *buff)
  14. {
  15. strncpy(buff, foo_tmp, foo_size);
  16. return foo_size;
  17. }
  18. static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr,
  19. const char *buff, size_t count)
  20. {
  21. foo_size = min(count, (size_t)FOO_SIZE_MAX);
  22. strncpy(foo_tmp, buff, foo_size);
  23. return count;
  24. }
  25. static struct kobj_attribute foo_attribute =
  26. __ATTR(foo, S_IRUGO | S_IWUSR, foo_show, foo_store);
  27. static struct attribute *attrs[] = {
  28. &foo_attribute.attr,
  29. NULL,
  30. };
  31. static struct attribute_group attr_group = {
  32. .attrs = attrs,
  33. };
  34. static struct kobject *kobj;
  35. static int myinit(void)
  36. {
  37. int ret;
  38. kobj = kobject_create_and_add("lkmc_sysfs", kernel_kobj);
  39. if (!kobj)
  40. return -ENOMEM;
  41. ret = sysfs_create_group(kobj, &attr_group);
  42. if (ret)
  43. kobject_put(kobj);
  44. return ret;
  45. }
  46. static void myexit(void)
  47. {
  48. kobject_put(kobj);
  49. }
  50. module_init(myinit);
  51. module_exit(myexit);
  52. MODULE_LICENSE("GPL");