Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to Linux sysfs node in C

Tags:

c

linux

From the shell I can activate the leds on my system like this:

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

I want to do the exact same thing from a C program, but I have not been able to find a simple example on how to accomplish this?

like image 549
flemming3233 Avatar asked May 05 '12 01:05

flemming3233


People also ask

What is sysfs in Linux?

sysfs is a pseudo file system provided by the Linux kernel that exports information about various kernel subsystems, hardware devices, and associated device drivers from the kernel's device model to user space through virtual files.

Is ioctl deprecated?

Adding more to confuse :" ioctl : However, ioctl is deprecated in the kernel, and you will find it hard to get any drivers with new uses of ioctl accepted upstream.

Is sysfs a system call?

The (obsolete) sysfs() system call returns information about the filesystem types currently present in the kernel.


3 Answers

Open the sysfs node like a file, write '1' to it, and close it again.

For example:

#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);
}
like image 124
Chris Stratton Avatar answered Nov 06 '22 05:11

Chris Stratton


Something like this:

#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;
}
like image 35
Chris Eberle Avatar answered Nov 06 '22 05:11

Chris Eberle


I'm not booted into my linux partition, but I suspect it goes something like this:

int f = open("/sys/class/leds/NAME:COLOR:LOCATION/brightness",O_WRONLY);
if (f != -1)
{
    write(f, "1", 1);
    close(f);
}
like image 38
selbie Avatar answered Nov 06 '22 03:11

selbie