为什么 CPP 中的 WaitForSingleObject 函数有这两种不同的行为 [英] Why those two different behaviors with WaitForSingleObject function in CPP

查看:37
本文介绍了为什么 CPP 中的 WaitForSingleObject 函数有这两种不同的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码示例:

#include #include #include <字符串>使用命名空间标准;无效主(){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 <<嗨!我完成了!";系统(暂停");}

当我尝试运行 cmd.exe 的代码时,在我关闭 cmd.exe 窗口之前,消息不会打印到屏幕上.

但是,当我尝试运行 calc.exe 的代码时,消息会在计算器进程结束之前打印到屏幕上.

为什么这两个可执行文件表现出不同的行为?

我想我对 WaitForSingleObject() 函数的理解错过了一些东西.

解决方案

我在 Windows 10 上尝试了您的代码,

如您所见,calc.exe 生成一个新进程然后结束,从而满足了等待.这就是为什么您会立即看到您的输出.这第二个过程是实际的计算器过程.就我而言,它位于以下路径:

C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1612.3341.0_x64__8wekyb3d8bbwe\Calculator.exe

I have the following code sample:

#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");
}

When I try the code running cmd.exe, the message isn't printed to the screen until I closed the cmd.exe window.

However, when I try the code running calc.exe instead, the message is printed to the screen before the calculator process ends.

Why are these two executables exhibiting different behaviors?

I think I missed something with my understanding of the WaitForSingleObject() function.

解决方案

I tried your code on Windows 10, and SysInternals Process Monitor shows the following:

As you can see, calc.exe spawns a new process and then ends, thus satisfying the wait. That is why you see your output immediately. This second process is the actual calculator process. In my case, it is located at this path:

C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1612.3341.0_x64__8wekyb3d8bbwe\Calculator.exe

这篇关于为什么 CPP 中的 WaitForSingleObject 函数有这两种不同的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆