C++ WaitForSingleObject在使用VC9编译器时挂起在VC12中
以下代码在VC9编译器中工作,而同一代码在VC12中不工作。你需要改变结构吗 问题来自WaitForSingleObject pi.hProcess,无限;线 在这一行之后,代码没有执行C++ WaitForSingleObject在使用VC9编译器时挂起在VC12中,c++,multithreading,pipeline,C++,Multithreading,Pipeline,以下代码在VC9编译器中工作,而同一代码在VC12中不工作。你需要改变结构吗 问题来自WaitForSingleObject pi.hProcess,无限;线 在这一行之后,代码没有执行 bool MyClass::check() { CSA_TRY { HANDLE hPipeOutputRead = NULL; HANDLE hPipeOutputWrite = NULL; PROCESS_INFORMAT
bool MyClass::check()
{
CSA_TRY
{
HANDLE hPipeOutputRead = NULL;
HANDLE hPipeOutputWrite = NULL;
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
SECURITY_ATTRIBUTES sa = {0};
// Create a pipe for the child's STDOUT.
sa.nLength = sizeof( SECURITY_ATTRIBUTES );
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
// Create pipe for standard output redirection.
CreatePipe( &hPipeOutputRead, // read handle
&hPipeOutputWrite, // write handle
&sa, // security attributes
0 // number of bytes reserved for pipe - 0 default
); // Create pipe for standard input redirection.
// Make child process use hPipeOutputWrite as standard out,
// and make sure it does not show on screen.
si.cb = sizeof(STARTUPINFO);
//si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hPipeOutputWrite;
si.hStdError = hPipeOutputWrite;
TCHAR commandLine[ MAX_PATH ] = _T("cmd.exe ver");
//spawn a new child process...
CreateProcess( NULL,
commandLine,
NULL, NULL,
TRUE, 0,
NULL, NULL,
&si, &pi
);
// Now that handles have been inherited, close it to be safe.
// You don't want to read or write to them accidentally.
CloseHandle( hPipeOutputWrite );
// Now capture the application output by reading hPipeOutputRead.
DWORD dwNumberOfBytesRead = 0;
CHAR szBuffer[ 65535 ];
CString conOut;
BOOL bTest = TRUE;
bTest = ReadFile( hPipeOutputRead, // handle of the read end of our pipe
&szBuffer, // address of buffer that receives data
256, // number of bytes to read
&dwNumberOfBytesRead, // address of number of bytes read
NULL // non-overlapped.
);
szBuffer[dwNumberOfBytesRead] = 0; // null terminate
conOut = szBuffer;
WaitForSingleObject ( pi.hProcess, INFINITE );
// Close all remaining handles
CloseHandle ( pi.hProcess );
CloseHandle ( hPipeOutputRead );
return true;
}
CSA_CATCH_ANY
{
//code
}
}
您正在启动进程cmd.exe ver。如果在资源管理器WindowsR中手动运行此操作,则可以看到cmd.exe ver打印出Windows版本,然后保持打开状态。程序将等待cmd.exe版本退出 因此,您需要关闭打开的cmd.exe版本(例如键入exit),或者将命令行更改为cmd.exe/c版本 代码中的另一个问题:您没有设置si.hStdInput
您确实应该添加错误检查,以查看哪些错误代码确实失败。它等待进程关闭。因为您通过了无限,它将继续等待,直到进程关闭。这是预期的行为。您没有检查代码中的任何地方的返回值,因此您实际上无法了解问题发生的位置;它甚至不知道你用的是哪种编译器。这表明问题在其他地方,例如,在可能触发您正在等待的事件的代码中。请提供可编译的。请比较一下。我试过使用cmd.exe/c ver和格式化字符串,例如:swprintf_s commandLine1,L%s/c%s,cmd,input;但它仍然不起作用。conOut=szBuffer;未获取版本的值。