Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Created April 8, 2012 13:25
Show Gist options
  • Select an option

  • Save nacho4d/2337291 to your computer and use it in GitHub Desktop.

Select an option

Save nacho4d/2337291 to your computer and use it in GitHub Desktop.
NSTask sample
#import <Foundation/Foundation.h>
void doTaskAndCapture(void);
void doTaskAndCapture()
{
@try
{
// Set up the process
NSTask *t = [[[NSTask alloc] init] autorelease];
[t setLaunchPath:@"/bin/ls"];
[t setArguments:[NSArray arrayWithObjects:@"-1", @"/", nil]];
// Set the pipe to the standard output and error to get the results of the command
NSPipe *p = [[[NSPipe alloc] init] autorelease];
[t setStandardOutput:p];
[t setStandardError:p];
// Launch (forks) the process
[t launch]; // raises an exception if something went wrong
// Prepare to read
NSFileHandle *readHandle = [p fileHandleForReading];
NSData *inData = nil;
NSMutableData *totalData = [[[NSMutableData alloc] init] autorelease];
while ((inData = [readHandle availableData]) &&
[inData length]) {
[totalData appendData:inData];
}
// Polls the runloop until its finished
[t waitUntilExit];
NSLog(@"Terminationstatus: %d", [t terminationStatus]);
NSLog(@"Data recovered: %@", totalData);
}
@catch (NSException *e)
{
NSLog(@"Expection occurred %@", [e reason]);
}
}
int main(int argc, char *argv[]) {
@autoreleasepool {
doTaskAndCapture();
}
}
@TomorJM
Copy link
Copy Markdown

TomorJM commented Jul 25, 2016

3Q for your sample

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