Created
January 18, 2013 19:09
-
-
Save valexa/4567367 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-(NSString*)execTask:(NSString*)launch args:(NSArray*)args | |
{ | |
if ([[NSFileManager defaultManager] isExecutableFileAtPath:launch] != YES){ | |
[bottomLeftLabel setStringValue:[NSString stringWithFormat:@"%@ not found",launch]]; | |
return nil; | |
} | |
NSPipe *stdout_pipe = [[NSPipe alloc] init]; | |
if (stdout_pipe == nil) { | |
NSLog(@"ERROR ran out of file descriptors at %@ %@",launch,[args lastObject]); | |
return nil; | |
} | |
NSTask *task = [[NSTask alloc] init]; | |
[task setLaunchPath:launch]; | |
[task setArguments:args]; | |
[task setStandardOutput:stdout_pipe]; | |
[task setStandardError:[task standardOutput]]; | |
NSFileHandle *stdout_file = [stdout_pipe fileHandleForReading]; | |
NSMutableString *output = [NSMutableString stringWithCapacity:1]; | |
NSTimer *timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:task selector:@selector(terminate) userInfo:nil repeats:NO]; | |
[task launch]; | |
NSData *inData = nil; | |
while ( (inData = [stdout_file availableData]) && [inData length] ) { | |
NSString *str = [[NSString alloc] initWithData:inData encoding:NSUTF8StringEncoding]; | |
if (str) { | |
[output appendString:str]; | |
[str release]; | |
if ([output length] > 8000000) { | |
NSLog(@"%@ data exceeds maximum, terminating, remaining output skipped",launch); | |
[output appendString:@"\n**Data exceeds maximum, remaining output skipped"]; | |
[task terminate]; | |
break; | |
} | |
} | |
} | |
[task waitUntilExit]; | |
[timeoutTimer invalidate]; | |
[stdout_file closeFile]; //unless we do this pipes are never released even if documentation says different | |
[stdout_pipe release]; //the object is actually overretained and never released | |
[task release]; | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment