我想用D编写的脚本打开和关闭嵌入式Linux板(BeagleBone Black)的led(字符设备)。
通过命令行,可以打开和关闭LED(例如,对于led"用户LED D2 0和#34;),使用:
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);
}
这是访问角色设备的合适方式还是有更好的选择?
答案 0 :(得分:3)
The unistd
calls are indeed the correct way to do it. A character device in Linux is a special kind of file and is accessed the same way: you open
it by path, then read
or write
to it, and close
it when finished.
Note that open
is actually inside core.sys.posix.fcntl
, while read
is in core.sys.posix.unistd
.
You could also use std.file.write()
from the D standard library to be a bit shorter. There's also chdir
in there. So your shell example would literally become:
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");
You don't strictly have to use std.file.write
as the full name with the import, I just like to since write
is such a common word it clears up which one we mean.
Anyway, this function just wraps up the unistd calls for you: it opens, writes the string, and closes all in one (just like the shell echo!).
One small difference is shell echo
sticks a \n
at the end of the string. I didn't do that here. If the code doesn't work, try "1\n" and such instead, maybe the device requires that. But I doubt it.
But the std.file.write
vs the core.sys.posix.unistd.write
aren't that much different. The former is more convenient, the latter gives more precise control over it.