Opening temporary files for std.process.spawnProcess input/output

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 25 11:09:15 PST 2015


On 02/25/2015 05:56 AM, wobbles wrote:

 > Hi,
 > Any reason why the following wont work?
 >
 > void main(string[] args)
 > {
 >      auto pidIn = File.tmpfile();
 >      auto pidOut = File.tmpfile();
 >      auto pid = spawnProcess(["ls", "./"], pidIn, pidOut,
 > std.stdio.stdout, null, Config.newEnv);
 >
 >      if(wait(pid) == 0)
 >          writefln("%s", pidOut.readln());
 > }
 >
 > The pidOut.readln() throws this exception:
 > object.Exception@/usr/include/dmd/phobos/std/stdio.d(1377): Attempt to
 > read from an unopened file.
 >
 > I figured tmpfile() would be open for read/write by default?
 > Also, theres no way to pass in args to File.tmpfile() to make them
 > read/write.
 >
 > Any ideas?

It looks like the file is closed when spawnProcess is finished. I don't 
know whether it is done by spawnProcess explicitly or whether it is a 
behavior for temporary files.

How about using a pipe? The following works:

import std.stdio;
import std.process;

void main(string[] args)
{
     auto pidIn = File.tmpfile();
     auto pidOut = pipe();
     auto pid = spawnProcess(["ls", "./" ],
                             pidIn, pidOut.writeEnd,
                             std.stdio.stdout, null, Config.newEnv);

     if(wait(pid) == 0)
         writeln(pidOut.readEnd.byLine);
}

Ali



More information about the Digitalmars-d-learn mailing list