如何强制杀死可可Mac OS X 10.5中的另一个应用程序

时间:2012-10-16 16:35:34

标签: cocoa kill sigkill nsworkspace appleevents

我已完成此任务,从我的应用程序中我需要 kill 我的另一个应用程序,问题是其他应用程序有终止确认对话 (没有要保存的关键数据,只确认用户退出的意图)。

  • 在10.6+上你将使用:

    bool TerminatedAtLeastOne = false;
    
    // For OS X >= 10.6 NSWorkspace has the nifty runningApplications-method.
    if ([NSRunningApplication respondsToSelector:@selector(runningApplicationsWithBundleIdentifier:)]) {
        for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.company.applicationName"]) {
            [app forceTerminate];
            TerminatedAtLeastOne = true;
        }
        return TerminatedAtLeastOne;
    }
    
  • 但是< 10.6这个常用的Apple事件:

    // If that didn‘t work either... then try using the apple event method, also works for OS X < 10.6.
    AppleEvent event = {typeNull, nil};
    const char *bundleIDString = "com.company.applicationName";
    
    OSStatus result = AEBuildAppleEvent(kCoreEventClass, kAEQuitApplication, typeApplicationBundleID, bundleIDString, strlen(bundleIDString), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, "");
    
    if (result == noErr) {
        result = AESendMessage(&event, NULL, kAENoReply|kAEAlwaysInteract, kAEDefaultTimeout);
        AEDisposeDesc(&event);
    }
    return result == noErr;
    

    不能强行退出!!!

那你能用什么?

1 个答案:

答案 0 :(得分:5)

您可以使用我在 cocoabuilder 上挖掘的这个简单代码:

// If that didn‘t work then try shoot it in the head, also works for OS X < 10.6.
NSArray *runningApplications = [[NSWorkspace sharedWorkspace] launchedApplications];
NSString *theName;
NSNumber *pid;
for ( NSDictionary *applInfo in runningApplications ) {
    if ( (theName = [applInfo objectForKey:@"NSApplicationName"]) ) {
        if ( (pid = [applInfo objectForKey:@"NSApplicationProcessIdentifier"]) ) {
            //NSLog( @"Process %@ has pid:%@", theName, pid );    //test
            if( [theName isEqualToString:@"applicationName"] ) {
                kill( [pid intValue], SIGKILL );
                TerminatedAtLeastOne = true;
            }
        }
    }
}
return TerminatedAtLeastOne;