Running external program from a D program [D2]

Jesse Phillips jessekphillips+D at gmail.com
Sun Feb 21 21:14:27 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

As you may have noticed by the comments to on bug 3158. exec()[1] calls
replace your process, this means it will not continue your program. To
get arround this you find that people will first fork()[2] and exec on
the child process.

In order to get your standard output you would use the dup2()[3] call.

Please note that I do not know how any of this will related to practices
on Windows. And sadly this is not D specific and actually C stuff.

1. http://www.opengroup.org/onlinepubs/007908799/xsh/exec.html
2. http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
3. http://www.mkssoftware.com/docs/man3/dup2.3.asp


More information about the Digitalmars-d-learn mailing list