Capture Delphi child-process output without a pipe deadlock
A redirected child can block when its output pipe fills. If the parent is waiting for the child to exit instead of reading the pipe, neither process can progress. Drain the output while the child runs, then collect its exit code.
The example below launches a second instance of itself as a trusted, finite console child. It merges stdout and stderr into one pipe, redirects stdin from NUL and captures 128 KiB of output plus a short marker. It targets Delphi 13 Win32 or Win64 and does not invoke a command shell.
Build the self-contained example
Create a Windows console application named CaptureDemo and replace its project source with this program. The parent creates its child without a console window. Run the parent from a terminal to see its summary.
program CaptureDemo;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils,
System.Classes;
procedure CloseOwnedHandle(var Handle: THandle);
begin
if (Handle <> 0) and (Handle <> INVALID_HANDLE_VALUE) then
CloseHandle(Handle);
Handle := 0;
end;
procedure WriteAll(Handle: THandle; const Bytes: TBytes);
var
Offset: Integer;
Written: DWORD;
begin
Offset := 0;
while Offset < Length(Bytes) do
begin
Win32Check(WriteFile(Handle, Bytes[Offset], Length(Bytes) - Offset, Written, nil));
if Written = 0 then
raise EWriteError.Create('No write progress.');
Inc(Offset, Written);
end;
end;
procedure RunChild;
begin
WriteAll(GetStdHandle(STD_OUTPUT_HANDLE), TEncoding.UTF8.GetBytes(StringOfChar('x', 131072)));
WriteAll(GetStdHandle(STD_ERROR_HANDLE), TEncoding.UTF8.GetBytes('done' + #10));
end;
function CaptureSelf(out ChildExitCode: DWORD): TBytes;
var
Security: TSecurityAttributes;
Startup: TStartupInfo;
ProcessInfo: TProcessInformation;
ProcessCreated: Boolean;
ReadPipe: THandle;
WritePipe: THandle;
InputHandle: THandle;
Executable: string;
CommandLine: string;
Buffer: array[0..4095] of Byte;
Received: DWORD;
ErrorCode: DWORD;
Output: TMemoryStream;
begin
Security := Default(TSecurityAttributes);
Security.nLength := SizeOf(Security);
Security.bInheritHandle := True;
InputHandle := 0;
ProcessInfo := Default(TProcessInformation);
ProcessCreated := False;
Output := nil;
Win32Check(CreatePipe(ReadPipe, WritePipe, @Security, 0));
try
Win32Check(SetHandleInformation(ReadPipe, HANDLE_FLAG_INHERIT, 0));
InputHandle := CreateFile('NUL', GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, @Security, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if InputHandle = INVALID_HANDLE_VALUE then
RaiseLastOSError;
Output := TMemoryStream.Create;
Startup := Default(TStartupInfo);
Startup.cb := SizeOf(Startup);
Startup.dwFlags := STARTF_USESTDHANDLES;
Startup.hStdInput := InputHandle;
Startup.hStdOutput := WritePipe;
Startup.hStdError := WritePipe;
Executable := ExpandFileName(ParamStr(0));
CommandLine := '"' + Executable + '" --child';
UniqueString(CommandLine);
Win32Check(CreateProcess(PChar(Executable), PChar(CommandLine), nil, nil, True, CREATE_NO_WINDOW, nil, nil, Startup, ProcessInfo));
ProcessCreated := True;
CloseOwnedHandle(ProcessInfo.hThread);
CloseOwnedHandle(WritePipe);
CloseOwnedHandle(InputHandle);
while True do
begin
if not ReadFile(ReadPipe, Buffer, SizeOf(Buffer), Received, nil) then
begin
ErrorCode := GetLastError;
if ErrorCode = ERROR_BROKEN_PIPE then
Break;
RaiseLastOSError(ErrorCode);
end;
if Received > 0 then
Output.WriteBuffer(Buffer, Received);
end;
if WaitForSingleObject(ProcessInfo.hProcess, INFINITE) <> WAIT_OBJECT_0 then
RaiseLastOSError;
Win32Check(GetExitCodeProcess(ProcessInfo.hProcess, ChildExitCode));
SetLength(Result, Output.Size);
if Length(Result) > 0 then
Move(Output.Memory^, Result[0], Length(Result));
finally
Output.Free;
CloseOwnedHandle(ReadPipe);
CloseOwnedHandle(WritePipe);
CloseOwnedHandle(InputHandle);
if ProcessCreated then
begin
CloseOwnedHandle(ProcessInfo.hThread);
CloseOwnedHandle(ProcessInfo.hProcess);
end;
end;
end;
procedure RunParent;
var
Bytes: TBytes;
ChildExitCode: DWORD;
begin
Bytes := CaptureSelf(ChildExitCode);
Writeln('Captured bytes=', Length(Bytes));
Writeln('Child exit=', ChildExitCode);
Writeln('Final marker=', BoolToStr(TEncoding.UTF8.GetString(Bytes).EndsWith('done' + #10), True));
end;
begin
try
if (ParamCount = 1) and (ParamStr(1) = '--child') then
RunChild
else
RunParent;
except
on E: Exception do
begin
Writeln('Error: ', E.Message);
ExitCode := 1;
end;
end;
end.
Expected parent output:
Captured bytes=131077
Child exit=0
Final marker=True
The large payload matters. A tiny βhelloβ can fit in the pipe buffer and conceal an incorrect wait-before-read design.
Follow handle ownership and completion
The child inherits the pipe's write end, but not its read end. The parent closes its own write copy immediately after launch. Otherwise a writer remains open and end-of-stream detection can wait forever even after the child exits.
Stdout and stderr share one pipe, which avoids waiting on one stream while the other fills. This loses their separate identities. If the application needs separate streams, drain both concurrently and define how their records are correlated. Do not read one to completion before starting the other.
CreateProcessW may modify its command-line buffer. UniqueString ensures this Delphi string has writable independent storage. The executable path is passed separately and repeated in quotes as the first command-line token. The only argument is the fixed --child switch, so this example is not a general quoting routine for arbitrary user input.
Keep the example's limits explicit
This synchronous capture is for a trusted finite child that creates no descendants. It has no overall deadline or cancellation mechanism and buffers all output in memory. An untrusted child, an endless stream or a descendant retaining the pipe writer needs a supervised process design with bounded storage, a deadline and explicit process-tree ownership.
The simple inheritance flag is appropriate only for this isolated console example. In an application with other inheritable handles or concurrent launches, use an explicit STARTUPINFOEX handle list and coordinate handle lifetime so unrelated handles cannot leak into the child.
Do not call this blocking function from the VCL main thread. A worker must finish or be safely cancelled before its buffers, callbacks and UI owner are released. Closing a process handle does not terminate that process, so an error path in a general process supervisor must also account for any child still running.
Finally, captured bytes need an encoding contract. This child explicitly writes UTF-8. An arbitrary legacy tool may use another code page, and bytes should not be decoded until that contract is known. Test nonzero exits, empty output, substantial stderr and output larger than the pipe buffer when adapting the pattern.
References




Question provenance
This article addresses Getting output from a shell/dos app into a Delphi app , asked by Jon Lennart Aasenden on Stack Overflow. The source question is licensed under CC BY-SA 3.0 . The explanation and examples here are newly authored for current Delphi. No answer text or code is reproduced.
Author: Herman Schoenfeld