简体   繁体   English

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

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

I'd like to get NSTask output as soon as it appears not waiting until process finishes. 我希望在进程结束后不等待NSTask输出。 I've found this answer but how it should be modified to get data ASAP? 我已经找到了这个答案但是应该如何修改以尽快获得数据? I think i should run background thread and wait for output all the time somehow. 我想我应该运行后台线程并一直等待输出。

You can register for the NSFileHandleDataAvailableNotification notification to read asynchronously from the task output. 您可以注册NSFileHandleDataAvailableNotification通知以从任务输出异步读取。 Example: 例:

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];

Alternatively, you can read on a background thread, for example with GCD: 或者,您可以在后台线程上阅读,例如使用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