c++ - 为什么 CPP 中 WaitForSingleObject 函数的这两种不同行为

标签 c++ windows

我有以下代码示例:

#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显示如下:

image

如您所见,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/

相关文章:

c++ - WxWidgets:大小调整器和浪费的空间

c++ - Qt - QCheckBox 不发出 stateChanged(int state) 信号

c++ - Code::Blocks 中的 OpenCV:应用程序无法正确启动 (0xc00000be)

windows - .bat - 从文件夹文件列表创建菜单

c++ - GetWindowlong 检查按钮样式

c++ - 编译期间 undefined reference

c++ - glTexImage2D 崩溃程序

c++ - 需要遍历整个对象,除了前两个元素。有设计模式吗?

windows - curl 将下载放在哪里?

java - 如何从网络调用程序?