Terminate a process by Cocoa
cocoa, macos, process, terminate
Solution
`-[NSWorkspace runningApplications]` returns an array of `NSRunningApplication` objects. `NSRunningApplication` has a method `-[NSRunningApplication terminate]`. So if you are looking for a specific application, you could terminate it like this:
-(void)killProcessesNamed:(NSString*)appName
{
for ( id app in [[NSWorkspace sharedWorkspace] runningApplications] )
{
if ( [appName isEqualToString:[[app executableURL] lastPathComponent]] )
{
[app terminate];
}
}
}
You could also call `forceTerminate` to force the app to quit without the normal quitting process. (It won't ask to save changes, etc.)
There are other methods of `NSRunningApplication` that you can use to make this process simpler depending on whether or not you're searching for a process based on bundle ID or PID.
Problem
If I terminate myself, just use the `[NSApp terminate: nil]`, it works very well. But if I want to terminate another process such as the active monitor, what should I do? To get the list of processes, I use ``` NSArray* processlist = [[NSWorkspace sharedWorkspace] runningApplications]; ``` Am I right? But how I can terminate a process by Cocoa, not use the `kill` or `KillProcess(<#const ProcessSerialNumber *inProcess#>)` or `killpd` or something like those, I just start learning Cocoa, so maybe I need some simple sample code or some keywords that can help me to find the documents. Thank you for your help.