Building a simple Hello World tool that works like a daemon
I have built a command line template (Foundation) in Xcode. It just writes "Hello World" to the console. It has only one main.m class. Here's the code:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[])
{
@autoreleasepool { // insert code here... NSLog(@"Hello, World!"); } return 0;
}
Now I want to start it as a daemon and write "Hello World" to the console every 10 seconds. So I moved product / binary to / tmp on my Mac. I created the following plist to run:
<?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>helloDaemon</string>
<key>ProgramArguments</key>
<array>
<string>/tmp/helloDaemon</string>
</array>
<key>StartInterval</key>
<integer>10</integer>
</dict>
</plist>
I downloaded the plist using launchctl, but I don't see any "Hello World" in the console. Instead, I get this:
11/03/2012 00:55:35.141 com.apple.launchd: (helloDaemon) Throttling respawn: Will start in 1 seconds
11/03/2012 00:55:45.141 com.apple.launchd: (helloDaemon) Throttling respawn: Will start in 2 seconds
11/03/2012 00:55:55.140 com.apple.launchd: (helloDaemon) Throttling respawn: Will start in 3 seconds
So what's wrong?
source to share
NSLog doesn't work because when you start the daemon it doesn't have any standard io sockets or files attached to it. They should be specially highlighted. A good resource for creating a proper daemon and for writing the console and syslog is in Advanced Mac OS X Programming (Chapter 20) by Dalrymple and Hillegass.
They define a skeletal program that solves the io problems you highlight. I remembered reading this some time ago and thought that maybe someday I will need it. The authors show a sample using the syslog.h lib, using openlog () and syslog () for simple communication. They also show some other lower level methods for communicating with files and even sockets (for servers, etc.).
I always appreciate it when someone can tell me how to do something rather than link to something, but in this case, this is the best I can do. good luck.
source to share
Just add to your launch plan
<key>StandardOutPath</key>
<string>/yourpath/sample.log</string>
You can tail -f
then.
More information here: http://developer.apple.com/library/mac/technotes/tn2083/_index.html#//apple_ref/doc/uid/DTS10003794-CH1-SUBSECTION39
source to share
With the following keys in the file, plist
I get most of the logs. But sometimes I get confused if I get all the NSLog
output in a log file. It seems to me that some line of logs is missing.
I'm not sure if all the NSLog
output LaunchDaemon
is being logged or if some of it is skipped due to system priority.
<key>StandardOutPath</key>
<string>/var/log/mydaemon.log</string>
<key>StandardErrorPath</key>
<string>/var/log/mydaemon.log</string>
source to share