Advertisement
xeritt

Sysfs read and write module linux kernel 4.15

Nov 22nd, 2018
344
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <linux/module.h>
  2. #include <linux/printk.h>
  3. #include <linux/kobject.h>
  4. #include <linux/sysfs.h>
  5. #include <linux/init.h>
  6. #include <linux/fs.h>
  7. #include <linux/string.h>
  8.  
  9. static struct kobject *example_kobject;
  10. static int test;
  11.  
  12. static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
  13.                       char *buf)
  14. {
  15.         return sprintf(buf, "%d\n", test);
  16. }
  17.  
  18. static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr,
  19.                       const char *buf, size_t count)
  20. {
  21.         sscanf(buf, "%du", &test);
  22.         return count;
  23. }
  24.  
  25.  
  26. static struct kobj_attribute foo_attribute =__ATTR(test, 0660, foo_show,
  27.                                                    foo_store);
  28.  
  29. static int __init sys_init (void)
  30. {
  31.         int error = 0;
  32.  
  33.         pr_debug("Module initialized successfully \n");
  34.  
  35.         example_kobject = kobject_create_and_add("systest",
  36.                                                  kernel_kobj);
  37.         if(!example_kobject)
  38.                 return -ENOMEM;
  39.  
  40.         error = sysfs_create_file(example_kobject, &foo_attribute.attr);
  41.         if (error) {
  42.                 pr_debug("failed to create the foo file in /sys/kernel/systest \n");
  43.         }
  44.  
  45.         return error;
  46. }
  47.  
  48. static void __exit sys_exit (void)
  49. {
  50.         pr_debug ("Module un initialized successfully \n");
  51.         kobject_put(example_kobject);
  52. }
  53.  
  54. MODULE_LICENSE("GPL");
  55. module_init(sys_init);
  56. module_exit(sys_exit);
Advertisement
RAW Paste Data Copied
Advertisement