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