Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Created May 23, 2015 05:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AquaGeek/8152ac3126ca54ccb311 to your computer and use it in GitHub Desktop.
Save AquaGeek/8152ac3126ca54ccb311 to your computer and use it in GitHub Desktop.
Objective-C command line tool
@import Foundation;
int main(int argc, const char * argv[])
{
__block BOOL keepRunning = YES;
// Configure a dispatch source to listen for SIGTERM
// Adapted from https://mikeash.com/pyblog/friday-qa-2011-04-01-signal-handling.html
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(source, ^{
printf("SIGTERM received!\n");
keepRunning = NO;
});
dispatch_resume(source);
// Tell sigaction to ignore SIGTERM - it's handled by the dispatch source above
struct sigaction action = {0};
action.sa_handler = SIG_IGN;
sigaction(SIGTERM, &action, NULL);
// Main run loop
@autoreleasepool {
NSLog(@"Hello, world!");
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
do {
@autoreleasepool {
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
} while (keepRunning);
}
return 0;
}
@AquaGeek
Copy link
Author

Because of the dispatch source, we don’t have to resort to the hacky “add a port to the run loop” fix to prevent the main loop from spinning out of control.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment