How to monitor a process on OS X? - objective-c

I am looking for a way to monitor the state of one of my applications on OS X. There's a number of components that I need to monitor such as the status of various communication channels. If they go down, the monitoring process should be able to warn the user both on screen and via a push notification.
XPC services look promising, but if the app crashes, I presume this will take out the service as well, or am I mistaken?
My preferred solution is something which would also monitor for unexpected termination, and restart the app if it happens.
What is the best way to do this?

I think monitoring communication channels, etc. must be done by the each specific components (processes). And if the unexpected error occur that component should exit immediately to ensure proper cleanup.
For processe monitoring, below Apple Technical Q&A document will be really helpful:
Technical Note TN2050: Observing Process Lifetimes Without Polling

You could write an app which starts your main application as a child process, and waits for it to exit. It could check the exit code, and then react according to your needs.
This approach is explained here: https://stackoverflow.com/a/78095/785411
To fork() some monitoring process to run your main application as a child process, this is explained here: https://stackoverflow.com/a/4327062/785411

I think you could possibly make use of the built in facilities Launchd and CrashReporter to achieve your requirements.
Launchd is the OS X system supervisor intended for launching and monitoring background processes, and would be typically used to run XPC services. Launchd agents can react to various system events, and can be configured to restart processes in the event of them crashing ( specified via the KeepAlive/SuccessfulExit key in the property list)
Launchd can be set to react to various system events as launch event, including monitoring files and directories, scheduled times, or listening to network connections.
CrashReporter is the OS X system facility that catches and logs all process crashes. It logs through the AppleSystemLogger facility and can be accessed with the syslog tools as documented in the linked TechNote. On Mountain Lion, user process crash reports end up in ~/Library/DiagnosticReports/ , with a crashlog and plist file pair created per crash event.
I think you could use these features in a couple of ways to achieve your requirement, if launchd is responsible for running the xpc services, it can take reponsibility for restarting them on crash events, and they can be dissociated from any app crashes.
You could write a launchd agent that responds to for crash events by montioring the crash report directory (e.g. using the QueueDirectories property) for new logs and re-launches your applicaton, or presents notifications.

If each process runs in its own thread you could run a watchdog program that monitors whether the threads are alive. A script that runs ps in a loop and parses the output could do it.
You can see the various options here. See for example -C to select by command name, and -m to show all threads.

Related

How to implement cron jobs in react native?

I am new to react-native and implementing simple app where app will monitor the mobile's clock time and should set some flags so as to notify user to perform some task when he starts the app.
I want to continuously monitor mobile's clock time as a background job in the react native app such that, when user opens the app and if specific time has already passed, it should set some flag to take future decision.
After some research over blogs, I found that react-native-background-task and/or background-timers can be used. But I am finding difficulty in implementing it. Can anyone help me with the implementation example for the same.
Thank you in advance.
So, from your post I'm going to assume a few things. One being you'll develop on Android as well as iOS, you just want to use a plugin (not code a module yourself).
Unfortunately, unless I'm mistaken - there's no simple answer and I'll explain.
As Android and iOS go forward they are starting to limit usage of Apps in the background, specifically Android goes into 'Doze' mode and iOS works in a similar fashion.
For Android, you'll need to consider a few things and I'll concentrate on them, as you'll need to know this before actually creating a RN app.
Doze Mode
Starting from Android 6.0 (API level 23), Android introduces two
power-saving features that extend battery life for users by managing
how apps behave when a device is not connected to a power source. Doze
reduces battery consumption by deferring background CPU and network
activity for apps when the device is unused for long periods of time.
App Standby defers background network activity for apps with which the
user has not recently interacted.
While the device is in Doze, apps' access to certain battery-intensive
resources is deferred until maintenance windows. The specific
restrictions are listed in Power Management Restrictions.
Doze and App Standby manage the behavior of all apps running on
Android 6.0 or higher, regardless whether they are specifically
targeting API level 23. To ensure the best experience for users, test
your app in Doze and App Standby modes and make any necessary
adjustments to your code. The sections below provide details.
Cruically, you'll need to note:
The system does not allow sync adapters to run.
The system does not allow JobScheduler to run.
So firstly for android, you'll (probably) need to ensure your app is in a 'whitelist'. You can check the requirements of the list here:
https://developer.android.com/training/monitoring-device-state/doze-standby
Or, you can access the maintenance window with a plugin like here:
https://github.com/transistorsoft/react-native-background-fetch
Testing
Android give you some tools to do so, mainly running:
$ adb shell dumpsys battery unplug
$ adb shell am set-inactive <packageName> true
Headless JS
You can check out headless tasks, which could suit your situation:
https://facebook.github.io/react-native/docs/headless-js-android
Caveats:
Although Android state that the operating system itself acts like documented, devices themselves can have software built in which essentially kills background processes. Nokia is one of the worst. So be aware of this.

Detect if a user logged in or logged out

I have a launch daemon that will need to spawn a tray icon in a users session on OSX. My current problem is: is there a way to get an event whenever a user logs in or logs out? Similar to using logind or consolekit on linux.
The tool you want is a LaunchAgent. LaunchAgents are automatically launched when a user logs in, and shut down when the log out. If you also have a LaunchDaemon, you can use a LaunchAgent to communicate to it from the user context. See Creating Launch Daemons and Agents for full details and how to set it up. Make sure to look at XPC services as well (in the same doc) to understand one way to communicate between processes. You can also use loopback networking, but XPC is more powerful and preferred when appropriate.
If you're building this kind of thing, you definitely want to read the entire Daemons and Services Programming Guide and also TN2083: Daemons and Agents. That tech note is probably the most important document you'll read for this kind of problem. OS X is not like Linux (or BSD) in this regard.

How to Turn Off Automatic Termination of Suspended Apps

I'm trying to debug my Windows Store App when it gets suspended (trying to prevent my server app from kicking my WSA client when it gets suspended and stops responding to keep-alive messages). But Windows keeps terminating my app almost immediately after it suspends it. Is there a way to prevent Windows from terminating suspended apps? I've searched the interwebs and the group policy editor for such a setting, but the best I can find is a setting to prevent it from auto-terminating apps on shutdown, which doesn't help me. And of course running in the debugger and pressing the Suspend button doesn't help either, since the app doesn't actually get suspended. I guess I could hack in some debug code to make it pretend to be suspended, but I'd prefer not to.
The command line tool PLMDebug, which is part of the Debugging Tools for Windows package, can be used to exempt an app from the Process Lifetime Management (PLM) policies. When put into debug mode, an app will not be subject to termination and will not be automatically suspended.
Usage:
plmdebug /enableDebug <PackageFullName> [OptionalDebuggerCommandLine]
Once you've exempted it from PLM automatic suspension and termination, you can use /suspend to force a manual suspension.

ios launch appstore from within my app causes my app to terminate

I'm trying to take users of My App to the AppStore for several different functions - like Upgrade to Full Version, Rate/Review or simply View another App I've developed. However, all of these are causing my App to Terminate when iTunes is launched on the device. I'm using some simple code and
have tried many combinations of URLs, all of which successfully get to where they are going. Here are the behaviors:
User clicks Rate App
Code directs them to the web via:
[[UIApplication sharedApplication] openURL:
[NSURL URLWithString:[[MyApp defaultApp] itunesLink]]];
My App goes to the background, and my delegate's applicationDidEnterBackground is called successfully
As iTunes is coming up, my App is terminated. Happens whether I run via X-Code or on the device directly.
When I quit out of the store and look at the running processes on the device, my App is still shown there. I know it has been terminated from X-Code console, and when I try to restart it it starts fresh.
I've tried the itunesLink as either itms://itunes.apple.com/app/ or with http - all of which get to the correct end point. If I use www.google.com it works fine and my App is NOT terminated, just sent to the background and the website is displayed OK.
Other points are that when I run via the simulator, the openURL call returns failure and doesn't open any URL.
Any insights as to why my App would be terminating? It's acting like an iOS security feature or something which is shutting my App down, but I thought what I was doing was pretty standard stuff.
If anyone has seen anything similar, I'd really appreciate advice on the situation.
Your app could be terminated for a number of reasons. The best thing is to look at the device console using Xcode's Organizer:
Your app may simply be terminated as a result of low memory notifications. As soon as it moves to the background and the app store launches (iTunes and the app store both use plenty of memory) it can be killed to free up memory. In this case you will set messages from "jetsam" like this:
<Notice>: jetsam: kernel termination snapshot being created
<Warning>: Application 'UIKitApplication:com.yourapp[0x6337]' exited abnormally with signal 9: Killed: 9
You should use the Activity Monitor in Instruments to see how much memory your application is using. iOS will terminate the most memory-intensive applications first, so you should try to reduce your app's memory footprint.

How do i create a agent/daemon that listens for NSDistributedNotifcations

I've created a command line cocoa program which creates an NSDistributedNotification, which other applications send notifications to. How can i keep the program running in an active state so it can still receive NSDistributedNotifications
I believe you are looking for Creating launchd Daemons and Agents on Mac OS X.