【问题标题】:Write to Linux sysfs node in C在 C 中写入 Linux sysfs 节点
【发布时间】:2012-05-05 10:26:45
【问题描述】:

从 shell 我可以像这样激活系统上的 LED:

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

我想用 C 程序做同样的事情,但我找不到一个简单的例子来说明如何做到这一点?

【问题讨论】:

    标签: c linux


    【解决方案1】:

    像打开文件一样打开 sysfs 节点,写入 '1',然后再次关闭。

    例如:

    #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);
    }
    

    【讨论】:

    • 这肯定会让我开始。还有一个问题,是否可以在 open 例程中使用变量而不是完整路径?
    • 当然 - 更改为 enable_led(char *pathname) 和 open(pathname, O_WRONLY) 然后从其他地方调用 if 作为 enable_led("/sys/whatever")
    • 应用程序将在哪个空间工作。驱动程序在内核模式下运行。我们是否必须将其编译为模块或其他东西。
    • 不,这是普通用户模式程序(但可能是特权程序)将少量数据设置到内核驱动程序中的一种方法。
    • 您的解决方案与使用标准 C 库中的 fopen() 有什么区别吗?
    【解决方案2】:

    类似这样的:

    #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;
    }
    

    【讨论】:

      【解决方案3】:

      我没有启动到我的 linux 分区,但我怀疑它是这样的:

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

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多