Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...