[fpc-devel] Running programs with output redirection

Sven Barth pascaldragon at googlemail.com
Sat Jul 16 23:08:23 CEST 2011


On 16.07.2011 22:37, Hans-Peter Diettrich wrote:
> There seems to exist an issue with (output) redirection, when I try to
> run an external program from code. What I want to achieve is this:
>
> In a Win32 console I can run
>  >diff -r dir1 dir2 > diff.txt
>
> When I use e.g. Exec('diff', args), diff complains about an excess
> argument, it works when "> diff.txt" is removed. With other functions I
> had less luck (ExecuteProcess, CreateProcess...), no output at all.
>
> Now I assume that output redirection is a shell feature, not available
> in direct invocation of an external program. Right?
>

In addition to the solution given by Andrew (namely using TProcess), I'd 
like to confirm that input/output redirection using ">", "<", "|", etc. 
is indeed a feature of the shell (be it DOS shell, NT command line or 
bash).
To use input/output redirection yourself in a program you need to point 
the Stdin, Stdout and/or Stderr handles of the called program to the 
source or sink you desire. For Windows that means passing handles for 
StdIn, StdOut and StdErr to CreateProcess. I don't know the procedure on 
Linux, but there the same basic concept applies. All this is 
encapsulated by TProcess.

Regards,
Sven



More information about the fpc-devel mailing list