1
0

hello-sysfs.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * hello-sysfs.c sysfs example
  3. */
  4. #include <linux/fs.h>
  5. #include <linux/init.h>
  6. #include <linux/kobject.h>
  7. #include <linux/module.h>
  8. #include <linux/string.h>
  9. #include <linux/sysfs.h>
  10. MODULE_LICENSE("GPL");
  11. static struct kobject *mymodule;
  12. /* the variable you want to be able to change */
  13. static int myvariable = 0;
  14. static ssize_t myvariable_show(struct kobject *kobj,
  15. struct kobj_attribute *attr,
  16. char *buf)
  17. {
  18. return sprintf(buf, "%d\n", myvariable);
  19. }
  20. static ssize_t myvariable_store(struct kobject *kobj,
  21. struct kobj_attribute *attr,
  22. char *buf,
  23. size_t count)
  24. {
  25. sscanf(buf, "%du", &myvariable);
  26. return count;
  27. }
  28. static struct kobj_attribute myvariable_attribute =
  29. __ATTR(myvariable, 0660, myvariable_show, (void *) myvariable_store);
  30. static int __init mymodule_init(void)
  31. {
  32. int error = 0;
  33. pr_info("mymodule: initialised\n");
  34. mymodule = kobject_create_and_add("mymodule", kernel_kobj);
  35. if (!mymodule)
  36. return -ENOMEM;
  37. error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
  38. if (error) {
  39. pr_info(
  40. "failed to create the myvariable file "
  41. "in /sys/kernel/mymodule\n");
  42. }
  43. return error;
  44. }
  45. static void __exit mymodule_exit(void)
  46. {
  47. pr_info("mymodule: Exit success\n");
  48. kobject_put(mymodule);
  49. }
  50. module_init(mymodule_init);
  51. module_exit(mymodule_exit);