Write in Linux sysfs node in C

From the shell, I can activate the LEDs in my system as follows:

#echo 1 > /sys/class/leds/NAME:COLOR:LOCATION/brightness 

I want to do the same from a C program, but I could not find a simple example of how to do this?

+4
source share
4 answers

Open sysfs node as a file, write '1' and close it again.

For instance:

 #include <stdio.h> #include <fcntl.h> void enable_led() { int fd; char d = '1'; fd = open("sys/class/leds/NAME:COLOR:LOCATION/brightness", O_WRONLY); write (fd, &d, 1); close(fd); } 
+7
source

Something like that:

 #include <stdio.h> int main(int argc, char **argv) { FILE* f = fopen("/sys/class/leds/NAME:COLOR:LOCATION/brightness", "w"); if (f == NULL) { fprintf(stderr, "Unable to open path for writing\n"); return 1; } fprintf(f, "1\n"); fclose(f); return 0; } 
+2
source

I do not boot into my Linux partition, but I suspect it looks something like this:

 int f = open("/sys/class/leds/NAME:COLOR:LOCATION/brightness",O_WRONLY); if (f != -1) { write(f, "1", 1); close(f); } 
+2
source

If you are looking for a breakthrough and not looking for performance or anything, just use the system() function to invoke the command in the same way as in the shell. Here is a link.

 /* system example */ #include <stdio.h> #include <stdlib.h> int main () { system( "echo 1 > /sys/class/leds/NAME:COLOR:LOCATION/brightness"); return 0; } 
0
source

Source: https://habr.com/ru/post/1410802/


All Articles