繁体   English   中英

在移动中使用NSTask获取流程输出?

[英]Getting process output using NSTask on-the-go?

我希望在进程结束后不等待NSTask输出。 我已经找到了这个答案但是应该如何修改以尽快获得数据? 我想我应该运行后台线程并一直等待输出。

您可以注册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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM