[英]Getting process output using NSTask on-the-go?
您可以注册NSFileHandleDataAvailableNotification
通知以从任务输出异步读取。 例:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/ls"];
[task setCurrentDirectoryPath:@"/"];
NSPipe *stdoutPipe = [NSPipe pipe];
[task setStandardOutput:stdoutPipe];
NSFileHandle *stdoutHandle = [stdoutPipe fileHandleForReading];
[stdoutHandle waitForDataInBackgroundAndNotify];
id observer = [[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification
object:stdoutHandle queue:nil
usingBlock:^(NSNotification *note)
{
// This block is called when output from the task is available.
NSData *dataRead = [stdoutHandle availableData];
NSString *stringRead = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding];
NSLog(@"output: %@", stringRead);
[stdoutHandle waitForDataInBackgroundAndNotify];
}];
[task launch];
[task waitUntilExit];
[[NSNotificationCenter defaultCenter] removeObserver:observer];
或者,您可以在后台线程上阅读,例如使用GCD:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/ls"];
[task setCurrentDirectoryPath:@"/"];
NSPipe *stdoutPipe = [NSPipe pipe];
[task setStandardOutput:stdoutPipe];
NSFileHandle *stdoutHandle = [stdoutPipe fileHandleForReading];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSData *dataRead = [stdoutHandle availableData];
while ([dataRead length] > 0) {
NSString *stringRead = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding];
NSLog(@"output: %@", stringRead);
dataRead = [stdoutHandle availableData];
}
});
[task launch];
[task waitUntilExit];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.