The Why and the How of Creating a Watchdog in Cocoa/Objective-C

白昼怎懂夜的黑 提交于 2019-12-12 08:16:16

问题


Happy Monday to you all!

Here is my situation. Any assistance greatly appreciated!

I have created an executable that when installed gets placed in the Launch Agents folder of the machine. In theory it should run perpetually, collecting data every second. It can stop when the machine is asleep, but restart when the computer is reactivated.

Here is my problem: sometimes the program just spontaneously stops, usually after a couple of days of running. If one restarts the computer then the program restarts and again runs for awhile before the same problem occurs.

I have no idea the reason for this problem, but was told by a friend that I could create a 'watchdog' that every minute would check if my executable is running. If it is not, then the watchdog will restart the executable.

Any pointers as to how to do this? My apps are written in Objective-C and Cocoa and run on Macs.

Thanks so much!


EDIT 1

I will explain how the app works to the best of my ability. It is basically a collection of methods written in C and Objective C that queries information about the system every second:

  • -bytes transmitted
  • -keyboard activity-
  • -mouse activity-
  • -percentage of harddrive used up
  • -process which has keyboard focus

...etc.

It does this using low level API's provided by the Apple Developer website. It writes the information to a file every second. Every hour the file is zipped up and a new file is created.

Please ask if more clarification is needed :)


EDIT 2

For those who are wondering, here is the plist file

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <dict>
     <key>Label</key>
     <string>com.Intel</string>
     <key>OnDemand</key>
     <true/>
     <key>ProgramArguments</key>
     <array>
         <string>/Library/LaunchAgents/Contents/Intel</string>
     </array>
     <key>RunAtLoad</key>
     <true/>
 </dict>
 </plist>

Thanks again....



回答1:


You can use launchd as your watchdog. Simply add the following key-value pair to your launchd plist file:

 <key>KeepAlive</key>
 <true/>

This will ensure that your process will be relaunched if it crashes or otherwise terminates. (It won't help if your process hangs, however.) For complete documentation on KeepAlive and other launchd keys, run "man launchd.plist" in Terminal.



来源:https://stackoverflow.com/questions/3650003/the-why-and-the-how-of-creating-a-watchdog-in-cocoa-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!