Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Created April 8, 2012 17:06
Show Gist options
  • Save nacho4d/2338521 to your computer and use it in GitHub Desktop.
Save nacho4d/2338521 to your computer and use it in GitHub Desktop.
Daemon in OSX Example
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
# pragma mark Daemon Protocol
@protocol DaemonProtocol
- (void)performWork;
@end
# pragma mark MyTask Object Conforms to Protocol
@interface MyTask : NSObject <DaemonProtocol>
@end;
@implementation MyTask
- (id)init
{
self = [super init];
if (self) {
// Do here what you needs to be done to start things
}
return self;
}
- (void)dealloc
{
// Do here what needs to be done to shut things down
[super dealloc];
}
- (void)performWork
{
// This method is called periodically to perform some routine work
NSLog(@"performing work ...");
}
@end
# pragma mark Setup the daemon
// Seconds runloop runs before performing work
#define kRunLoopWaitTime 1.0
BOOL keepRunning = TRUE;
void sigHandler(int signo)
{
NSLog(@"sigHandler: Received signale %d", signo);
switch (signo) {
case SIGTERM: keepRunning = FALSE; break; // SIGTERM means we must quit
default: break;
}
}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSLog(@"Daemong running");
signal(SIGHUP, sigHandler);
signal(SIGTERM, sigHandler);
MyTask *task = [[MyTask alloc] init];
while (keepRunning) {
[task performWork];
CFRunLoopRunInMode(kCFRunLoopDefaultMode, kRunLoopWaitTime, false);
}
[task release];
NSLog(@"daemon existing");
}
return 0;
}
/*
<?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>KeepAlive</key><false/>
<key>Label</key><string>com.nacho4d.mydaemon</string>
<key>ProgramArguments</key><array><string>/Library/MyDaemon/Daemon/</string></array>
<key>RunAtLoad</key><true/>
<key>ServiceIPC</key><false/>
<key>StandardErrorPath</key><string>/Library/Logs/MyDaemon.log</string>
<key>StandardOutPath</key><string>/Library/Logs/MyDaemon.log</string>
</dict>
</plist>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment