【发布时间】:2018-09-14 15:52:31
【问题描述】:
我正在尝试使用Pipe 的fileHandleForReading 的readabilityHandler 来读取Process 的standardOutput 和standardError。然而,terminationHandler 被调用的那一刻实际上是之前我的readabilityHandler 第一次被调用的那一刻。
我不确定进程为什么会这样做,但这意味着我没有获取所有数据,因为我假设进程终止意味着所有输出都已刷新到管道。由于情况并非如此,有没有办法让我知道何时没有更多输出可供读取?我认为这涉及检查 FileHandle 是否仍然打开,但我不知道'没有看到一个 API。
这是我的代码的基本概念的示例:
let stdOutPipe = Pipe()
let stdErrPipe = Pipe()
stdOutPipe.fileHandleForReading.readabilityHandler = { stdOutFileHandle in
let stdOutPartialData = stdOutFileHandle.readDataToEndOfFile()
guard !stdOutPartialData.isEmpty else {
print("Time to read, but nothing to be read?") // happens a lot
return
}
self.tempStdOutStorage.append(stdOutPartialData)
}
stdErrPipe.fileHandleForReading.readabilityHandler = { stdErrFileHandle in
let stdErrPartialData = stdErrFileHandle.readDataToEndOfFile()
guard !stdErrPartialData.isEmpty else {
print("Time to read, but nothing to be read?") // happens a lot
return
}
self.tempStdErrStorage.append(stdErrPartialData)
}
process.standardOutput = stdOutPipe
process.standardError = stdErrPipe
process.terminationHandler = { process in
notifyOfCompleteRead(stdOut: self.tempStdOutStorage, stdErr: self.tempStdErrStorage)
}
mySpecializedDispatchQueue.async(execute: process.launch)
【问题讨论】:
标签: swift cocoa nstask nsfilehandle nspipe