I'm trying to implement a way to detect whether another instance of an application has already been started, and have been tinkering with: 1. Shared memory 2. Named mutexes 3. Named pipes
Seems all of these have the flaw that if the "main" application crashes, the "IPC" object will be left hanging making all future instances of the application think that there is another instance active (until a reboot). Ideally I'd like to have an object that is automatically removed when the process is terminated, whether normally or by a crash.
Ideas?
I've seen this done by using a file and file locking. The main app check for the existence of a file in /tmp. If the file is currently locked then the application is already running. If the file does not exist or is not locked then it is not running. Depending upon the OS you need to do this in a fashion that is atomic to avoid race conditions.
This way if a program crashes the file is automatically closed by the OS.