views:

406

answers:

3

Hey all,

How can I terminate another app that is running in cooca. Let's say I have iTunes running, and I type in quit in my app, it would quit itunes. "iTunes" is just an example, it could be anything the user wants. I can open any app from my application, but I want to know how to close any app running.

thanks

kevin

+1  A: 

For high-level applications like iTunes, based on Carbon or Cocoa, they're going to respond to Applescript. "Quit" is part of the standard package. You just need to send:

tell application "iTunes" to quit

There are lots of ways to do that. The simplest to implement is to make a system call to osascript:

osascript -e 'tell application "iTunes" to quit'

You can go up from there to more powerful tools like Apple Events, which would be very appropriate for this problem. You could even go so far as Scripting Bridge, but for terminating an app, that would be overkill.

This will only work for programs that respond to Applescript, but that should be any program that you would see in your dock (and which I assume you mean by "applications"). For lower-level processes like daemons, you need other techniques like launchctl or kill, but we can talk about those if you need them.

Rob Napier
+11  A: 

AppleScript is a pretty high-level way to send a single Quit event. SIGTERM is a pretty brute-force, low-level way.

The correct way to quit another application is to obtain its Process Serial Number (psn) and send it a kAEQuitApplication Apple event with these two lines of code:

result = AEBuildAppleEvent( kCoreEventClass, kAEQuitApplication, typeProcessSerialNumber, &currentProcessPSN,
sizeof(ProcessSerialNumber), kAutoGenerateReturnID, kAnyTransactionID, &tAppleEvent, &tAEBuildError,"");
result = AESend( &tAppleEvent, &tReply, kAEAlwaysInteract+kAENoReply, kAENormalPriority, kNoTimeOut, nil, nil );

You can do this from C, C++, or Objective-C, and you have to link with CoreServices.framework.

cdespinosa
+5  A: 

If you're running on Mac OS X 10.6, Snow Leopard, you can use the new NSRunningApplication terminate method.

Jon Hess
ok I get this error when debugging here's my codeNSRunningApplication *selectedApp = appName; [selectedApp terminate];
Kevin
You probably want to call [[[NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.iTunes"] objectAtIndex:0] terminate]. You can't assign j. random string constant to a variable of a completely different class.
cdespinosa