hello-sysfs.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. static struct kobject *mymodule;
  11. /* the variable you want to be able to change */
  12. static int myvariable = 0;
  13. static ssize_t myvariable_show(struct kobject *kobj,
  14. struct kobj_attribute *attr, char *buf)
  15. {
  16. return sprintf(buf, "%d\n", myvariable);
  17. }
  18. static ssize_t myvariable_store(struct kobject *kobj,
  19. struct kobj_attribute *attr, const char *buf,
  20. size_t count)
  21. {
  22. sscanf(buf, "%d", &myvariable);
  23. return count;
  24. }
  25. static struct kobj_attribute myvariable_attribute =
  26. __ATTR(myvariable, 0660, myvariable_show, myvariable_store);
  27. static int __init mymodule_init(void)
  28. {
  29. int error = 0;
  30. pr_info("mymodule: initialized\n");
  31. mymodule = kobject_create_and_add("mymodule", kernel_kobj);
  32. if (!mymodule)
  33. return -ENOMEM;
  34. error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
  35. if (error) {
  36. kobject_put(mymodule);
  37. pr_info("failed to create the myvariable file "
  38. "in /sys/kernel/mymodule\n");
  39. }
  40. return error;
  41. }
  42. static void __exit mymodule_exit(void)
  43. {
  44. pr_info("mymodule: Exit success\n");
  45. kobject_put(mymodule);
  46. }
  47. module_init(mymodule_init);
  48. module_exit(mymodule_exit);
  49. MODULE_LICENSE("GPL");