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.
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.
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...
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;
}