csysfsprocfs

proper way of writing to /sys or /proc filesystem in c


what is a proper way of writing to /proc or /sys filesystem in linux in c ?

Can I write as I would in any other file, or are there special considerations I have to be aware of?

For example, I want to emulate echo -n mem > /sys/power/state. Would the following code be the right way of doing it?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

    FILE *f;

    f = fopen("/sys/power/state", "w");

    if(f == NULL) {
        printf("Error opening file: /sys/power/state\n");   
        exit(1);             
    }

    fprintf(f,"%s","mem");

    fclose(f);
}

Solution

  • Your approach lacks some error handling in the write operation.

    The fprintf (or fwrite, or whatever you prefer to use) may fail, e.g. if the kernel driver behind the sysfs file doesn't like what you're writing. E.g.:

    echo 17 > /sys/class/gpio/export
    -bash: echo: write error: Invalid argument
    

    In order to catch those errors, you MUST check the output of the fprintf to see if all characters that you expected to write were written, and you should also check the output of ferror(). E.g. if you're writing "mem", fprintf should return 3 and there should not be any error set in the stream.

    But one additional thing is missing: sysfs are not standard files. For the previous write error to be returned correctly you MUST disable buffering in your stream, or otherwise the fprintf (or fwrite)) may happily end without any error. You can do that with setvbuf like this just after the fopen.

    setvbuf (f, NULL, _IONBF, 0);