piping processes

Regan Heath regan at netmail.co.nz
Thu Dec 1 03:10:00 PST 2011


On Wed, 30 Nov 2011 23:35:58 -0000, NMS <nathanmswan at gmail.com> wrote:

> Is there a cross-platform way to create a new process and get its i/o  
> streams? Like java.lang.Process?

No.  It different on windows and unix platforms, tho most/many of the unix  
platforms are similar.

std.process is rather limited in it's current incarnation but I think  
Steve is working on a bit update..

I have misplaced the pipestream and processstream code I wrote ages ago  
which did what you want, otherwise I'd just send it to you.  So, best I  
can do is describe the process.

On windows you call Win32 functions, requiring you link with the  
appropriate windows libs - to find out which ones search for the function  
names I am about to describe in MSDN online.

To start a child process with input handles..
  - You call CreatePipe for each input (stdin, stdout, stderr) this gives  
you 2 handles for each pipe, one handle is for the child process, the  
other for the parent (think of the cans on string you used to use as a kid)
  - Pro tip; you now want to call DuplicateHandle on the parent handle for  
each pipe to remove 'inheritance' - this stops the child process  
inheriting the handle (which would result in 2 open handles to the pipe,  
and closure of the parent handle would not be detected by the child).   
After duplication you close the original parent side inheritable handles.
  - Call CreateProcess to start the process.  In flags specify  
STARTF_USESTDHANDLES and assign the child end of each of the pipes to each  
input.
  - Close the child pipe handles (in the parent) that were passed to  
CreateProcess.

To read from the child
  - Call PeekNamedPipe or ReadFile on the parent end of the pipe that was  
passed to the child as it's stdout.

To write to the child
  - Call WriteFile on the parent end of the pipe that was passed to the  
child as it's stdin.

To detect the child termination
  - CreateProcess returns a thread handle and a process handle, you can  
wait on either with WaitForSingleObject (I typically use the process  
handle and close the thread handle immediately after starting the child).


I haven't done this sort of thing on unix for ages and I have no good code  
to hand so someone else will have to help you out with this..

R


-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list