How to get NSTask output in Cocoa?

I use NSTask in Cocoa APP, and I need to be able to get the result and store it in an array or something like that ... I execute 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

Thank you so much!

+5
source share
1 answer

You want to use - [NSTask setStandardOutput:] to attach NSPipe to a task before starting it. The pipe contains two file descriptors, the task will be written to one end of the pipe, and you will read from the other. You can schedule a file descriptor to read all data from a background task and notify you of completion.

It will look something like this (compiled to 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]];
}

, .

+16

All Articles