1
0

hello-sysfs.c 1.5 KB

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