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.

Pascal
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:

Plain text
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

Creating a Child Process with Redirected Input and Output - Win32 apps
The example in this topic demonstrates how to create a child process using the CreateProcess function from a console process.
https://learn.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
CreateProcessW function (processthreadsapi.h) - Win32 apps
Creates a new process and its primary thread. The new process runs in the security context of the calling process. (Unicode)
https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
CreatePipe function (namedpipeapi.h) - Win32 apps
Creates an anonymous pipe, and returns handles to the read and write ends of the pipe.
https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe
Process Creation Flags (WinBase.h) - Win32 apps
The following process creation flags are used by the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, and CreateProcessWithTokenW functions. They can be specified in any combination, except as noted.
https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags

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