用 C 写入 Linux sysfs 节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10458166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write to Linux sysfs node in C
提问by flemming3233
From the shell I can activate the leds on my system like this:
从 shell 中,我可以像这样激活系统上的 LED:
#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?
我想从 C 程序中做完全相同的事情,但我找不到一个简单的例子来说明如何做到这一点?
采纳答案by Chris Stratton
Open the sysfs node like a file, write '1' to it, and close it again.
像打开文件一样打开 sysfs 节点,向其写入“1”,然后再次关闭。
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);
}
回答by Chris Eberle
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;
}
回答by selbie
I'm not booted into my linux partition, but I suspect it goes something like this:
我没有启动到我的 linux 分区,但我怀疑它是这样的:
int f = open("/sys/class/leds/NAME:COLOR:LOCATION/brightness",O_WRONLY);
if (f != -1)
{
write(f, "1", 1);
close(f);
}