hello-sysfs.c 1.5 KB

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