๐Ÿ”ธ Introduction

A developer tries to redirect stdout to a file using SetStdHandle, and suddenly the app crashes with ERROR_INVALID_TARGET_HANDLE (0x72). This error occurs when a system call receives a handle that isn’t valid.


๐Ÿ”ธ Technical Breakdown

  • Symbolic Constant: ERROR_INVALID_TARGET_HANDLE
  • Decimal: 114
  • Hexadecimal: 0x00000072
  • Meaning:
    The handle specified in a redirection or duplication function (e.g., SetStdHandle, DuplicateHandle) is invalid, NULL, or improperly opened.

๐Ÿ”ธ In-Depth: Why It Happens

๐Ÿ”น Low-Level Causes:

  • Uninitialized handles.
  • Passing INVALID_HANDLE_VALUE or a closed handle.
  • Using a handle type not suited for SetStdHandle.

๐Ÿ”น High-Level Causes:

  • Incorrectly redirected standard output in service or background process.
  • Misuse of CreateFile when opening files for standard handle replacement.

๐Ÿ”ธ Solutions

โœ… Ensure Handle Is Valid

Always validate handles returned from system functions:

c

if (hFile == INVALID_HANDLE_VALUE) {
// handle error
}

โœ… Use SetStdHandle with Correct Access

c

HANDLE hFile = CreateFileW(L"output.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
SetStdHandle(STD_OUTPUT_HANDLE, hFile);

โœ… Check Error Codes After Redirection

c

if (!SetStdHandle(STD_OUTPUT_HANDLE, hFile)) {
DWORD dwErr = GetLastError(); // check for ERROR_INVALID_TARGET_HANDLE
}

โœ… Close All Handles Properly

Avoid use-after-close scenarios that can silently fail.


๐Ÿ”ธ References


๐Ÿ”ธ Metadata

  • SEO Title: Fix ERROR_INVALID_TARGET_HANDLE (0x00000072): Resolve Handle Redirection Errors in Windows
  • Meta Description: ERROR_INVALID_TARGET_HANDLE (0x00000072) signals invalid I/O redirection or handle misuse. Learn how to properly manage and validate system handles.
  • Hashtags:
    #SetStdHandle #ERROR_INVALID_TARGET_HANDLE #Win32API #WindowsHandles #ConsoleRedirection #MicrosoftDocs #HandleError #WindowsDebug #DuplicateHandle #SystemAPI #0x00000072
  • Tags:
    fix error 0x00000072, SetStdHandle error, invalid handle passed, CreateFile misuse, stdout redirect fail, Windows system handles, DuplicateHandle invalid, process I/O redirection, Win32 error 0x00000072, INVALID_HANDLE_VALUE, 0x00000072,
  • SEO Keywords:
    ERROR_INVALID_TARGET_HANDLE, SetStdHandle error, duplicate handle invalid, fix error 0x00000072, INVALID_HANDLE_VALUE Windows, file handle not valid, stdout redirection error, Windows system error 0x00000072, Win32 API handle error