Redirecting console I/O: SetHandleInformation fails with invalid handle


I am trying to figure out how to adapt this sample in order to redirect the output of a console window to a text box inside another process.

Unfortunately, it seems that the reader will never receive any input.

Further debugging shows that the call to SetHandleInformation always aborts with Error 6: Invalid Handle. The value of hPipeOutRd does not look bad, it is something like 0x00000244.

This reproduces the matter:

int main(int argc, char *argv[])
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;

    int result = 0;
    HANDLE hPipeOutRd = INVALID_HANDLE_VALUE; // This end is passed to the pipe reader
    HANDLE hPipeOutWr = INVALID_HANDLE_VALUE; // This end is passed to the child process

    if ( result == 0 && !::CreatePipe( &hPipeOutRd, &hPipeOutWr, &sa, 4096 ) ) 
        result = -1; 
        printf("Error: %u\r\n", GetLastError() ); 
    if ( result == 0 && !::SetHandleInformation( &hPipeOutRd, HANDLE_FLAG_INHERIT, 0 ) ) // This fails with invalid handle
        result = -1; 
        printf("Error: %u\r\n", GetLastError() );  

    return result;

Any ideas why?

asked on Stack Overflow Mar 3, 2017 by antipattern • edited Mar 3, 2017 by antipattern

1 Answer


A HANDLE is already a pointer. You don't take its address unless it is an out parameter.

Just take the & out of your SetHandleInformation call.

answered on Stack Overflow Mar 3, 2017 by Zan Lynx

User contributions licensed under CC BY-SA 3.0