如何做 Windows 处理继承

How to do Windows Handle Inheritance

我有父进程和子进程,在父进程中我声明句柄将被继承,如 http://msdn.microsoft.com/en-us/library/windows/desktop/ms724466%28v=vs.85%29.aspx:

...
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
sa.bInheritHandle = TRUE; 
sa.lpSecurityDescriptor = NULL;
// Create a pipe for the Parent process's STDOUT.  
if ( ! CreatePipe(&hChildReadPipe, &hParentWritePipe, &sa, 0) )
{
    _tprintf(_T("Error creating Pipe\n")); 
}
...

// Start the child process. 
if( !CreateProcess(
        _T("..\Debug\Child.exe"),
        _T("hChildReadPipe"),   // Command line.
        NULL,                   // Process handle not inheritable.
        NULL,                   // Thread handle not inheritable.
        TRUE,                   // Set handle inheritance to TRUE.
        CREATE_NEW_CONSOLE,     // No creation flags.
        NULL,                   // Use parent's environment block.
        NULL,                   // Use parent's starting directory.
        &si,                    // Pointer to STARTUPINFO structure.
        &pi )                   // Pointer to PROCESS_INFORMATION structure.
    )
    {
        printf( "\nCreateProcess failed (%d).\n", GetLastError() );
    return FALSE;
    }

我的问题是如何获取通过命令行传递给子进程的 hChildReadPipe 句柄,在 MSDN 中他们建议使用 GetCommandLine() 但这只是 returns 命令行字符串,我如何转换它字符串到可用的 HANDLE?

我尝试了 CreateFile() 但它不起作用...

谢谢

我的第一个建议是阅读 Creating a Child Process with Redirected Input and Output

但是,如果您的要求不涉及标准输入或标准输出(或其他相关句柄),那么您可以将句柄转换为整数值 (UINT_PTR value = (UINT_PTR)hChildReadPipe;) 并将其作为字符串传递给命令行(__ultoa())。然后 child 将需要从命令行 (UINT_PTR value = strtoul()) 读取整数值并将其转换回 HANDLE (HANDLE hChildReadPipe = (HANDLE)value;).

要记住的重要一点是 excerpt on handle inheritance from Microsoft"An inherited handle ... has the same value ..."