Ric*_*újo 2 c windows inheritance handle
我有父进程和子进程,在父进程中我声明句柄将被继承,如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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何获取命令行传递给子进程的hChildReadPipe句柄,在MSDN中他们建议使用GetCommandLine(),但这只返回命令行字符串,如何将此字符串转换为可用的HANDLE?
我试过CreateFile()但它不起作用......
谢谢
我的第一个建议是阅读使用重定向输入和输出创建子进程.
但是,如果您的要求是不要触摸stdin或stdout(或其他相关的HANDLE),那么您可以将句柄转换为整数值(UINT_PTR value = (UINT_PTR)hChildReadPipe;)并将其作为字符串(__ultoa())传递给命令行.然后,子进程需要读取命令行(UINT_PTR value = strtoul())的整数值并将其强制转换回HANDLE(HANDLE hChildReadPipe = (HANDLE)value;).
要记住的重要事情是从微软处理继承摘录,"An inherited handle ... has the same value ...".