Preventing multiple instances of a mac app

We have a developer signed mac app that users install using an installer.

Our use case is to keep the app running all the time, even when user terminates it forcefully. To achieve this, we copy a launch agent plist file to /Library/LaunchAgents with RunAtLoad=true, and KeepAlive=true, during the installation. We load/bootstrap this agent at the end of the installation using launchctl script.

This serves our purpose very well. ie. 1) app is launched whenever any user logs in to the machine 2) app is relaunched automatically, even if user terminates it.

By default, when the app is already running and users launches it again, there is only one instance of it which is totally fine and is expected.

But there are some situations, when after a machine restart or user login, we have observed two instances of the same app running at the same time. Yes, two app icons in the dock and two app windows.

But we discovered that if the user has selected 'Open at Login' by right clicking on it's icon in the Dock, and then restarts the machine or re-login, two instances are launched.

We suspect that one instance is autolaunched by our keepalive/runatload launch agent. And the other one perhaps by the 'Open at Login' action. But the user experience is very bad in this situation.

We tried to add LSMultipleInstancesProhibited key to the app plist, but it didn't work.

Preventing multiple instances of a mac app
 
 
Q