So I basically just want to know when a foreign application starts and closes.
Right now I’m just running a loop that checks this:
- (BOOL)isRunning:(int)AppPid{
ProcessSerialNumber psn = { kNoProcess, kNoProcess };
OSStatus err = GetProcessForPID(AppPid, &psn);
if ( err != noErr ){
NSLog(@"Error %d", err);
return NO;
}
return YES;
}
The issue i’m running into is that if I call this function too much (lets say 50 times in a second), it will eventually fail and say the process isn’t running, when it actually is.
This could happen once every 10 minutes, or 5 times in a row, it’s unpredictable.
My question – is there another easy way via Cocoa/Objective-C to determine if a process is running (that doesn’t involve a system task calling ps, as doing that 50 times/second isn’t smart)?
There’s
[NSRunningApplication runningApplicationWithProcessIdentifier:].If you want to know when a particular application launches and exits, there are some notifications on NSWorkspace you can listen for, specifically
NSWorkspaceDidLaunchApplicationNotificationandNSWorkspaceDidTerminateApplicationNotification.You can then check the
NSWorkspaceApplicationKeyof the notification’suserInfodictionary to retrieve theNSRunningApplicationthat corresponds to the launched or terminated application, which you can match via bundle ID (or whatever) to determine if it’s the application you’re interested in.