I want to terminate some applications execution after an amount of time passed. I am polling NSWorkspace's runningApplications for a lack of something to observe on (if the application is just running, does it notify of anything?)
My issue is that applications are only sometimes terminated, sometimes they take a few seconds after the time they should be closed (according to an internal timer) and sometimes they do not terminate at all!
I tried using both terminate and forceTerminate methods.
In the code snippet, apps_ is a vector of strings containing application names. It is updated regularly by another thread and its data is received before running the below code. They all run inside an es_handler_block_t
NSArray<NSRunningApplication *> *running_apps = [NSWorkspace sharedWorkspace].runningApplications;
for (const auto &app_ : apps_) {
//std::cout << app_ << "\n";
for (NSRunningApplication *app in running_apps) {
if ([[NSString stringWithUTF8String:app_.c_str()] isEqualToString:[app.executableURL lastPathComponent]] ) {
std::string app_name = [[app.executableURL absoluteString] UTF8String];
std::cout << "Terminating app " << app_name << "\n";
bool res_f = [app forceTerminate];
bool res_t = [app terminate];
LOG_DBG("Force terminate: %d", res_f);
LOG_DBG("Terminate: %d", res_t);
break;
}
}
}
I read in runningApplications documentation that "this property will only change when the main run loop runs in a common mode". What does it mean?
I suppose it is something related to runningApplication's polling, as inserting a breakpoint in the above code (before the if check) and then resuming execution instantly kills the application that would otherwise still run.
I am not blocking the main function. I only have an Endpoint Security class for the framework, networking is done on some other thread, and I return
with NSApplicationMain(argc, argv);
What could be the issue? Thanks.
EDIT: I am leveraging the Cocoa Framework to create an agent that displays only in the system tray and it has root privileges. Preventing apps from launching is successfully achieved using the Endpoint Security Framework, but I did not find a reliable way to kill already running applications that works every time.
LATER EDIT: I managed to add an observer to [[NSWorkspace sharedWorkspace] notificationCenter]
, but what notification should I subscribe to for an application that is running? I tried with hide but it does not work if the user just clicks on the red window button, only if he hides the app from the dock. But I still want to close it even if there is no interaction between the user and the running app.