1

我为NSFileHandleReadCompletionNotification.

我用两个独立的管道设置了标准 I/O。

NSPipe * input  = NSPipe.new;
NSPipe * output = NSPipe.new;

[serverTask setStandardInput:input];
[serverTask setStandardOutput:output];

我启动一个执行 Java jar 的 NSTask,并开始读取数据。

[[serverTask.standardOutput fileHandleForReading] readInBackgroundAndNotify];

我不断读取数据并将数据附加到一个NSTextView新数据中:

- (void)serverLogHasChanged:(NSNotification *)notification
{
    [[serverTask.standardOutput fileHandleForReading] readInBackgroundAndNotify];

    NSData * newData = [notification.userInfo objectForKey:NSFileHandleNotificationDataItem];

    if (newData != nil && availableData != newData)
    {
        NSMutableString * serverLogString = [NSMutableString stringWithString:serverLog.string];

        [serverLogString appendString:[NSString.alloc initWithData:newData encoding:NSUTF8StringEncoding]];
        [serverLog setString:serverLogString];
        [serverLog.enclosingScrollView.contentView scrollPoint:NSMakePoint(0, NSMaxY(serverLog.enclosingScrollView.contentView.bounds))];
    }

    newData = availableData;
}

但是,我得到了奇怪的输出到NSTextView

在此处输入图像描述

那些“>”字符应该是实际输出的行,但输出最终会出现在 Xcode 的控制台中。

换句话说,控制台打印输出而不是我NSPipe的,它只打印输出新行的指示。

4

1 回答 1

4

如上所述,这是添加捕获标准错误输出的情况。我最近遇到了类似的问题。我通过执行以下操作解决了它:

NSPipe *pipe = [NSPipe pipe];
[javaTask setStandardOutput:pipe];
[javaTask setStandardError:pipe];
NSFileHandle *fileHandleForReading = [pipe fileHandleForReading];

[javaTask launch];

NSData *result = [fileHandleForReading readDataToEndOfFile];

NSString *output = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];

谢谢,CRD 的帮助。

于 2012-02-23T12:16:47.233 回答