Created
April 8, 2012 13:25
-
-
Save nacho4d/2337291 to your computer and use it in GitHub Desktop.
NSTask sample
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/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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
3Q for your sample