在objective-c中调用terminal命令

/ 0评 / 1

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:

- (void)launch {
    NSTask *task = [[[NSTaskalloc] init] autorelease];
    [task setLaunchPath:@"/path/to/command"];
    [task setArguments:[NSArray arrayWithObjects:..., nil]];
    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardOutput:outputPipe];
    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotificationobject:[outputPipe fileHandleForReading]];
    [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
    [task launch];
}
- (void)readCompleted:(NSNotification *)notification {
    NSLog(@"Read data: %@", [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:NSFileHandleReadToEndOfFileCompletionNotificationobject:[notification object]];
}

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

发表评论

邮箱地址不会被公开。 必填项已用*标注