I'm trying to redirect stdout to a string with Swift, to collect whatever is passed to the print function. I've read through a few resources that suggest my approach should be working, however, the following proof of concept script only outputs "Starting":
import Foundation
let outPipe = Pipe()
var outString = "Initial"
outPipe.fileHandleForReading.readabilityHandler = { fileHandle in
outString += String(data: fileHandle.availableData, encoding: .utf8)!
}
print("Starting")
// Redirect
setvbuf(stdout, nil, _IONBF, 0)
dup2(outPipe.fileHandleForWriting.fileDescriptor, STDOUT_FILENO)
print("Captured")
freopen("/dev/stdout", "a", stdout)
print(outString)
Any ideas where I've gone wrong? All help is appreciated!