tags:

views:

453

answers:

3

Hi all, I am developing an application in cocoa,which needs to check whether that app is already running at start up.If already running then i need to quit the new instance ..Is there any way to do this..Looking for a perfect solution

A: 

My answer here is not specific for object-c implementation but as a general approach. In *nix like systems, a daemon will normally create a pid file at somewhere to indicate its existence. If a daemon does not allow multiple instances, then another fire of the app should first check whether such a pid file exists, if so, exist itself.

jimx
Worth noting that this answer only applies to daemons, not actual applications. Moreover, it doesn't apply to a daemon specifically for Mac OS X; the recommended way is to check in with launchd instead. http://developer.apple.com/technotes/tn2005/tn2083.html
Peter Hosey
Although I used the word 'daemon', pid file pattern does not have to be restricted for single instance daemon. In user interactive apps, normally, it is implemented via .lockfile under the apps profile. It almost serves the same purpose as daemon's pidfile. Thanks for the link. Launchd is recommended and looks like it may all depends on how to specify the configuration. But I am still lock to see where it guarantees to prevent multi-instance to launch.
jimx
A: 

you could popen() an instance of the ps command and look for the application name. if you find it, shut down the new one. maybe not the fastest way, but it works :-)

klez
+1  A: 

It sounds like you are saying you want to keep multiple instances of your cocoa app from running at the same time. Normally cocoa apps do not allow multiple instances to be running at the same time so typically you would not need to perform this check. Is there some specific circumstance in which you are finding that a cocoa app is being run concurrently?

In general, a cocoa way to solve this look at launchedApplications in NSWorkspace. This returns an NSArray containing a dictionary for each launched application. You can loop through the array to see if the app you are looking for is already running. I would advise that you use the value with the key NSApplicationBundleIdentifier which will have a value like "com.mycompany.myapp" rather than looking for the name. If you need to find the bundle identifier for an app you can look at its info.plist file in the app package.

Jon Steinmetz