问题描述
- 创建子进程句柄继承问题
-
SECURITY_ATTRIBUTES sa; HANDLE hRead, hWrite; std::string result; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = FALSE;//TRUE; if (!CreatePipe(&hRead,&hWrite,&sa,0)) { cout << "创建管道失败!" << endl; return FALSE; } STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags |= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; // 使用默认的IO句柄 si.hStdOutput = hWrite; si.hStdError = hWrite; si.wShowWindow = SW_SHOWNORMAL; // 隐藏控制台窗口 PROCESS_INFORMATION pi = {0}; TCHAR para[100] = L"cmd.exe /c tree"; if (!CreateProcess(NULL, para, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { cout << "创建进程失败!" << endl; return FALSE; }
运行完CreateProcess之后出现提示:
Tree Walk Utility已停止工作如果sa.bInheritHandle = TRUE, 就OK.
想请教个中原因, 不胜感激!
解决方案
问题在于,当你设定sa.bInheritHandle = FALSE;之后,你又试图做
si.hStdOutput = hWrite;
si.hStdError = hWrite;
解决方案二:
windows核心编程中有讲,SECURITY_ATTRIBUTES 中的bInheritHandle如果为TRUE表示继承,否则不继承!规定如此
时间: 2024-11-08 17:50:46