This is an old post, but I was looking for a good way to do this and did not stumble upon it.
Perhaps this will help someone in a similar situation.
I do this on Windows, but maybe it is also possible for osx / linux using the named pthread clutches, although I donโt know the policy on how such mutexes are handled if the application is completed, which is crucial for this technique.
The problem with using one flag is that it does not work in a situation where there can be several instances of the application:
- Application 1 starts. Checks the "Do not close the flag correctly" box.
- Application 2 is running. He sees that it is not closed, because the flag is set and thinks that a failure occurred when it was not there.
This is a little difficult to do, and there are probably several ways to do this, but this method still works (at least on Windows):
Create a global mutez with the new GUID / UUID as the name.
The GUID is different for each instance of the application, so each of them will have a unique named mutex. The GUID is written to a file containing a list of GUIDs. If the application disconnects correctly, you remove the GUID from the file and the mutex closes. If the application crashes or is terminated, the GUID is not deleted from the file, but the mutex is destroyed by the OS without an application that should do this.
When you launch the application, you can run the GUID in the list and call OpenMutex on them and mutexes that do not exist (GetLastError returns ERROR_FILE_NOT_FOUND). Any non-existent mutexes indicate that a failure / termination has occurred. All GUIDs that have this property can be removed from the list at this time.
Another thing you can do is remove the bad GUIDs from the list when the job completes correctly. This turns into the following situation:
- Appendix 1 is starting
- Launch Application 2
- Crash Application 1
- Appendix 2 completed successfully
- Application 3 starts.
When application 3 is running, it should not publish that a failure has occurred because the last shutdown was good.
I also used a kind of spinlock to gain access to a file containing GUIDs that will execute after a period of time and will not add manual for the file to the file. In such cases, it is probably best to run the application anyway and lose the crash detection rather than not running the application at all.
Other caveats should keep the file locked while requesting and updating the file to avoid race conditions. In windows, this prevents the use of stl filestreams, since you will need to trim the file after reading it, while maintaining exclusive access to the file.