Running external program from a D program [D2]

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Mon Feb 22 01:25:05 PST 2010


Jonathan M Davis wrote:
> Okay, I'm looking to be able to run an external program from within my D 
> program. The library functions for this appear to be in std.process. You 
> have system() and various versions of execv(). system() makes a call in 
> shell. execv() executes the program without a shell.
> 
> What I'd _like_ to be able to do is run the program without a shell so that 
> I don't have to worry about escaping special characters in file names, and I 
> want to have access to the output from the program. This poses two problems.
> 
> 1. Is there a way to run a program without the shell and without the call 
> terminating the program (per bugzilla 3158, execv takes over your program 
> and terminates it when it's done, in spite of what the documentation says - 
> it's certainly been killing my programs when I've tried)? The only way that 
> I see to do that at the moment is to spawn a separate thread and run execv 
> in it. I'd prefer to just make the call and wait for it to return. Is there 
> a way to do so?
> 
> 2. Is there a way to get at what the called program sends to stdout? I'm 
> afraid that I don't have a clue how to get at that.
> 
> Any help would be appreciated. Thanks.
> 
> - Jonathan M Davis


std.process has an undocumented function spawnvp(), which I believe does 
the same as the C function _spawnvp(), i.e. it forks and executes a 
child process, optionally waiting for it to finish.  The signature is:

   int spawnvp(int mode, string pathname, string[] argv);

where 'mode' is one of P_WAIT or P_NOWAIT.  You can use this, but be 
aware that there is most likely a reason for it being undocumented. :)


When the new concurrency framework is in place, I assume this will 
improve.  To begin with, the D developers are focusing on multithreading 
with message passing, such as:

   auto threadID = spawn(&threadFunction);
   threadID.send(message);

But they have said that this will be extended to multiprocess message 
passing, and then I almost expect something like this:

   auto procID = spawnProcess("firefox");
   procID.send(message);

It's some time into the future, though. ;)

-Lars


More information about the Digitalmars-d-learn mailing list