Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

objective c - How to receive output of NSTask in Cocoa?

I'm using NSTask in my Cocoa APP , and I need to be able to get result, and store it in Array, or something... I'm executing terminal commands from APP, and I need outputs for them.

NSString *path = @"/path/to/command";
NSArray *args = [NSArray arrayWithObjects:..., nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

//After task is finished , need output

Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to use -[NSTask setStandardOutput:] to attach an NSPipe to the task before launching it. A pipe holds two file handles, the task will write to one end of the pipe, and you'll read from the other. You can schedule the file handle to read all of the data from the background task and notify you when it's complete.

It will look something like this (compiled in stack overflow):

- (void)launch {
    NSTask *task = [[[NSTask alloc] init] autorelease];
    [task setLaunchPath:@"/path/to/command"];
    [task setArguments:[NSArray arrayWithObjects:..., nil]];
    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardOutput:outputPipe];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];
    [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
    [task launch];
}

- (void)readCompleted:(NSNotification *)notification {
    NSLog(@"Read data: %@", [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}

If you also want to capture the output of standard error, you can use a second pipe and notification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...