๐ธ 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_VALUEor 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
CreateFilewhen opening files for standard handle replacement.
๐ธ Solutions
โ Ensure Handle Is Valid
Always validate handles returned from system functions:
cif (hFile == INVALID_HANDLE_VALUE) {
// handle error
}
โ
Use SetStdHandle with Correct Access
cHANDLE 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
cif (!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
- SetStdHandle โ Microsoft Learn
- Handle Management โ Microsoft Docs
- DuplicateHandle โ Microsoft Learn
๐ธ 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
