今日工作中遇到一问题,当我执行完ShellExecuteEx函数后,发现他不等待ShellExecuteEx调出的执行程序执行完毕,就继续其他代码行。为此特地学习了一下,总结方法有二:
方法一:
...... // 代码行
SHELLEXECUTEINFO sei;
memset(&sei, 0, sizeof(SHELLEXECUTEINFO));
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpVerb = _T("open");
sei.lpFile = _T("aa.exe");
sei.nShow = SW_SHOWDEFAULT;
ShellExecuteEx(&sei);
WaitForSingleObject(sei.hProcess, INFINITE);
CloseHandle(sei.hProcess);
...... // 代码行
方法二:
通过CreateProcess创建一个进程,然后进行等待。
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// 创建子进程
if( !CreateProcess( NULL, // No module name (use command line).
"MyChildProcess", // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // 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.
)
{
ErrorExit( "CreateProcess failed." );
}
// 等待子进程退出
WaitForSingleObject( pi.hProcess, INFINITE );
// 关闭句柄
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );