Created
May 23, 2015 05:34
-
-
Save AquaGeek/8152ac3126ca54ccb311 to your computer and use it in GitHub Desktop.
Objective-C command line tool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.