2

I want to write a program in C++ that can open a .exe program and I want to know when it's close by the user. I know that I can open a program by this code:

system ("start C:\\AAA.exe");

However I don't know how can I check if the program closed.

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
Mahdi Salmanzadeh
  • 321
  • 1
  • 3
  • 9
  • http://stackoverflow.com/questions/1591342/c-how-to-determine-if-a-windows-process-is-running –  Jan 29 '16 at 09:55
  • 1
    Possible duplicate of [c - exit status of a program running in background](http://stackoverflow.com/questions/13320159/c-exit-status-of-a-program-running-in-background) – gmuraleekrishna Jan 29 '16 at 09:56

2 Answers2

4

On Windows if you use CreateProcess() instead of system() to start a new process. Simplified code:

PROCESS_INFORMATION processInformation;
CreateProcess(..., &processInformation);

In PPROCESS_INFORMATION you find its handle. With its handle you can wait it's terminated (to mimic how system() works):

WaitForSingleObject(processInformation.hProcess, INFINITE);

Or periodically check its status getting its exit code (if any, see also How to determine if a Windows Process is running?) if your code has to run together with child process:

DWORD exitCode;
BOOL isActive = STILL_ACTIVE == GetExitCodeProcess(processInformation.hProcess, &exitCode);

Don't forget to close handle (even if process already terminated):

CloseHandle(processInformation.hProcess);

Note that with that code you don't know the reason process terminated. It may be because user closed its window, because it terminated by itself or because it crashed. For a GUI application you can hook its main window messages looking for WM_CLOSE (to detect user actions), WM_QUIT (application did it) and attaching an handler with SetUnhandledExceptionFilter() (to detect unhandled errors). It's not 100% reliable but it may be material for another question...

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
1

Calling system ("C:\AAA.exe"); you can block until process AAA.exe finished.

If it is not acceptable, you can call system ("C:\AAA.exe"); in separate thread, and check is it finished or not.

#include <thread>


void threadRoutine()
{
    ::system("C:\AAA.exe");
}

int main()
{
    std::thread systemCall(threadRoutine);
    //do some work here
    systemCall.join();
    //you are sure that AAA.exe is finished
    return 0;
}
mooncheese
  • 124
  • 1
  • 1
  • 4