我有以下代码示例:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "cmd.exe";
ShExecInfo.lpParameters = "";
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
std::cout << "hi! Im done!";
system("pause");
}
当我尝试运行 cmd.exe
的代码时,在我关闭 cmd.exe
窗口之前,消息不会打印到屏幕上。
但是,当我尝试运行 calc.exe
的代码时,消息会在计算器进程结束之前打印到屏幕上。
为什么这两个可执行文件表现出不同的行为?
我想我对 WaitForSingleObject()
函数的理解遗漏了一些东西。
最佳答案
我在 Windows 10 上试过你的代码,SysInternals Process Monitor显示如下:
如您所见,calc.exe
生成一个新进程然后结束,从而满足等待。这就是为什么您会立即看到输出的原因。第二个进程是实际的计算器进程。在我的例子中,它位于这条路径:
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1612.3341.0_x64__8wekyb3d8bbwe\Calculator.exe
关于c++ - 为什么 CPP 中 WaitForSingleObject 函数的这两种不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495791/