【问题标题】:How can I access a linux character device with D?如何使用 D 访问 linux 字符设备?
【发布时间】:2017-08-04 17:54:11
【问题描述】:

我想使用 D 编写的脚本打开和关闭嵌入式 linux 板 (BeagleBone Black) 的 LED(字符设备)。

通过命令行可以打开和关闭一个 LED(例如,对于 LED“USER LEDS D2 0”):

cd /sys/class/leds/beaglebone:green:usr0
echo none > trigger
echo 1 > brightness
echo 0 > brightness

echo none > trigger 禁用默认的“心跳”闪烁)

在第 93 页的 D Cookbook 中,我找到了有关如何通过 C 接口进行 linux 系统调用的信息,如下所示:

void main(){
   import core.sys.posix.unistd;  // analogous to #include <unistd.h>
   string hello = "Hello, world!";
   write(1 /*stdout file descriptor*/, hello.ptr, hello.length);
}

这是访问字符设备的合适方法还是有更好的替代方法?

【问题讨论】:

  • 顺便说一句:使用这里描述的 std.process stackoverflow.com/questions/6876553/… 对我也不起作用......
  • LDC 和 DMD 都为我编译了这个 sn-p(LDC 1.3.0 和 DMD 2.075.0)。你得到什么样的错误?
  • 用 dmd 我得到hello.d(3): Error: unexpected ( in declarator hello.d(3): Error: basic type expected, not 1 hello.d(3): Error: found '1' when expecting ')' hello.d(3): Error: no identifier for declarator write(_error_) hello.d(3): Error: semicolon expected following function declaration hello.d(3): Error: declaration expected, not ','
  • 发布的代码和你编译的完全一样吗?它错过了string hello = ... 行上的分号。
  • 不,它不缺少分号。和上面一模一样……

标签: linux-device-driver d


【解决方案1】:

unistd 调用确实是正确的方法。 Linux 中的字符设备是一种特殊的文件,访问方式相同:您通过路径open 它,然后通过readwrite 访问它,完成后close 它。

注意open实际上在core.sys.posix.fcntl中,而readcore.sys.posix.unistd中。

您也可以使用 D 标准库中的 std.file.write() 来缩短一点。里面还有chdir。所以你的 shell 例子实际上会变成:

import std.file;
chdir("/sys/class/leds/beaglebone:green:usr0");
std.file.write("trigger", "none"); // write "filename", "data string"
std.file.write("brightness", "1");
std.file.write("brightness", "0");

您不必严格使用 std.file.write 作为导入的全名,我只是喜欢,因为 write 是一个如此常见的词,它明确了我们的意思。

无论如何,这个函数只是为你包装了 unistd 调用:它打开、写入字符串,然后关闭所有内容(就像 shell echo!)。

一个小的区别是shell echo 在字符串的末尾粘贴了一个\n。我在这里没有这样做。如果代码不起作用,请尝试“1\n”等,也许设备需要。但我对此表示怀疑。

std.file.writecore.sys.posix.unistd.write 并没有太大区别。前者更方便,后者控制更精准。

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2012-06-25
    • 2014-01-23
    • 2021-10-31
    • 2019-05-19
    相关资源
    最近更新 更多