Search code examples
linuxmodulelinux-kernelsysfs

How to read a string from a sysfs attribute file a Linux kernel module?


Basically, I want to have a configuration file, e.g. "myconfigfile" that contains a string of characters, for example "abcdefg".

I want to read this string in as a value in my kernel module. That is, I want to have a char* in my code that gets the value "abcdefg" from that file. From what I understand, I should use sysfs. Here are my questions:

  1. Do I just create the file and move it into /sys/module/path/to/my/module directory ?
  2. If I have the file available, how exactly do I read the value? Say the file is called "myconfigfile". I read this documentation but frankly, I don't understand it.

Solution

  • Your actual problem is that you want to configure something in your module.

    Reading a configuration file does not solve that problem, it just introduces another problem.

    To configure something in your module, use a module parameter:

    #include <linux/kernel.h>
    #include <linux/module.h>
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Sefu");
    
    static char *my_param = "default";
    module_param(my_param, charp, 0444);
    MODULE_PARM_DESC(my_param, "my little configuration string");
    
    int init_module(void)
    {
        printk(KERN_INFO "The parameter is: %s\n", my_param);
        return 0;
    }
    
    void cleanup_module(void)
    {
    }
    

    To set that value, load your module with something like

    modprobe mymodule my_param=whatever
    

    or put this line into some .conf file in /etc/modprobe.d/:

    options mymodule my_param=whatever