Communicating with external processes

If you are performing a task and encounter a stage where another program does an excellent job, is it possible to call that program and use the results in your D program? The answer is yes. Here, we'll look at using std.process to run another program and send it input and read its output.

How to do it…

Let's communicate with external processes by executing the following steps:

  1. Import std.process.
  2. Call pipeProcess to start the program you want, storing the return value. You may want to put the external process name in a version block, as the same program might not be available on other operating systems.
  3. Use the returned handles to communicate with the process as though it was a file.
  4. Close the handles when you are finished.
  5. Wait for the process to exit.

The code is as follows:

import std.process, std.stdio;
auto info = pipeProcess("child_program");
scope(exit) wait(info.pid);
info.stdin.writeln("data to send to the process");
info.stdin.close();
foreach(line; stdout.byLine)
     writeln("Received ", line, " from child.");

The child program may be anything that writes to its stdout handle. For example, have a look at the following code:

import std.stdio;
void main() {
    writeln("Hello!");
    writeln("Second line.");
}

Calling the function from the preceding program will print the following:

Received Hello! from child.
Received Second line. from child.

How it works…

Phobos' std.process module includes several cross-platform functions to communicate with other processes. It can run programs, spawn shells, and create pipes on standard handles. Once created, the resultant pipes are presented as std.stdio.File objects and can be written to (in the case of the stdin handle, you write to the child program's input) the input and read from (for stdout and stderr, reading the child process' output) the output like any other file.

You can also access the operating system or C functions yourself, bypassing the Phobos functions. This is necessary if you need asynchronous I/O with the process.

You may also wish to define an RPC protocol to use over your pipes, to call functions as well as pass data. Any network application protocol can be adapted to work with local processes and pipes. For example, there are D bindings to Apache Thrift that may be of use.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.20