How can I access the Linux character device using D?

I would like to turn the LED (character device) of an embedded Linux board (BeagleBone Black) on and off using a script written in D.

The LED can be switched on and off via the command line (for example, for the "USER LEDS D2 0" LED) with:

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

      

( echo none > trigger

disables the default "heartbeat" blinking)

In the D Cookbook on page 93 I found information on how to make Linux system calls through the C interface, for example:

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

      

Is this a suitable way to access the character device, or are there better alternatives?

+3


source to share


1 answer


Calling is unistd

really the right way to do it. A character device in Linux is a special kind of file that is accessed in the same way: you are open

on a path, then read

or write

to it, and then close

on completion.

Note what is open

actually inside core.sys.posix.fcntl

, but read

is in core.sys.posix.unistd

.

You can also use std.file.write()

from the D standard library to be a little shorter. There also chdir

. So your shell example will 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 have to use it std.file.write

as the full name with imports, I just like it, as it write

is such a general word that it clears up what we mean.

Either way, this function just completes the unistd calls for you: it opens, writes a string, and closes all in one (just like shell echo!).

One small difference is that the shell echo

inserts the line \n

at the end of the line. I didn't. If the code doesn't work, try "1 \ n" and, instead, it might require the device. But I doubt it.

But std.file.write

vs the are core.sys.posix.unistd.write

not very different from each other. The former is more convenient, the latter gives more precise control over it.

+3


source







All Articles