Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

macos - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is extremely easy in Snow Leopard:

- (void)deduplicateRunningInstances {
    if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[[NSBundle mainBundle] bundleIdentifier]] count] > 1) {
        [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey]] 
                         defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];

        [NSApp terminate:nil];
    }
}

See http://blog.jseibert.com/post/1167439217/deduplicating-running-instances-or-how-to-detect-if for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...