我正在尝试使用 aPipe
来fileHandleForReading
读取readabilityHandler
astandardOutput
和standardError
a Process
。但是,terminationHandler
调用的时刻实际上是在第一次调用my 的时刻之前readabilityHandler
。
我不确定进程为什么要这样做,但这意味着我没有获取所有数据,因为我假设进程终止意味着所有输出都已刷新到管道。既然不是这样,有没有办法告诉我什么时候没有更多的输出可供读取?我认为这涉及检查 aFileHandle
是否仍然打开,但我没有看到用于此的 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)