重定向控制台 I/O:SetHandleInformation 失败,句柄无效

ant*_*ern 1 c++ winapi

我试图弄清楚如何调整此示例,以便将控制台窗口的输出重定向到另一个进程内的文本框。

不幸的是,读者似乎永远不会收到任何输入。

进一步的调试表明,对的调用SetHandleInformation始终会中止Error 6: Invalid Handle。的价值hPipeOutRd看起来不错,类似于 0x00000244。

这再现了这个问题:

int main(int argc, char *argv[])
{
    SECURITY_ATTRIBUTES sa;
    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;
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Zan*_*ynx 5

HANDLE 已经是一个指针。除非它是一个输出参数,否则您不会获取它的地址。

只需从 SetHandleInformation 调用中取出 & 即可。