gpt4 book ai didi

c - 如何进行 Windows 句柄继承

转载 作者:可可西里 更新时间:2023-11-01 09:53:07 32 4
gpt4 key购买 nike

我有父进程和子进程,在父进程中我声明句柄将被继承,如 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() 但这只会返回命令行字符串,我如何将此字符串转换为可用的句柄?

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

谢谢

最佳答案

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

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

要记住的重要一点是 excerpt on handle inheritance from Microsoft , “继承的句柄...具有相同的值...”

关于c - 如何进行 Windows 句柄继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27744601/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com