Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Created April 8, 2012 13:25
Show Gist options
  • Save nacho4d/2337291 to your computer and use it in GitHub Desktop.
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();
}
}
@tonysup
Copy link

tonysup commented Feb 24, 2013

how does nstask write some infomation.for example. open a ssh,and when server give a "please input your passwd",then write the passwd into the nstask.

@bumper314
Copy link

Look at the "expect" command

@TomorJM
Copy link

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