Search code examples
macosboostresourcesmacos-carbonlaunch

How to detect whether an OS X application is already launched


Normally an application bundle on OS X can only be started once, however by simply copying the bundle the same application can be launched twice. What's the best strategy to detect and stop this possibility?

On Windows this effect can simply be achieved by the application creating a named resource at launch and then exit if the named resource can't be created, indicating that another process is running that has already created the same resource. These resources are released in a reliable way on Windows when the application quits.

The problem I have seen when researching this is that the APIs on OS X keep state in the file system and thus makes the strategy used on windows unreliable, i.e lingering files after an improper exit can falsely indicate that the application is already running.

The APIs I can use to achieve the same effect on OS X are: posix, carbon and boost.

Ideas?


Solution

  • A low-level solution is to use flock().

    Each instance would attempt to lock a file on startup, and if the lock fails then another instance is already running. Flocks are automagically released when your program exits, so no worries about stale locks.

    Note that whatever solution you choose, you need to make a conscious decision about what it means to have "multiple instances". Specifically, if multiple users are running your app at the same time, is that ok?