Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why those two different behaviors with WaitForSingleObject function in CPP

Tags:

c++

windows

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.

like image 329
fdwfg wdfwdfv Avatar asked May 31 '26 12:05

fdwfg wdfwdfv


1 Answers

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

image

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
like image 159
marcinj Avatar answered Jun 02 '26 02:06

marcinj