Leaking Pipes with Swift and External Executables

Observed with MacOS 12.4/Xcode 13.4.1/Swift 5

There are quite a lot of tutorials out there covering the basics of running external executables from within Swift and, with very little effort, it’s quite easy to throw together something like this…

import Foundation

let wrappedUname = Process()
wrappedUname.executableURL = URL(fileURLWithPath: "/usr/bin/uname")
wrappedUname.arguments = ["-v"]
let unameOutputPipe = Pipe()
let unameErrorPipe = Pipe()
wrappedUname.standardOutput = unameOutputPipe
wrappedUname.standardError = unameErrorPipe
do{
    try wrappedUname.run()
} catch {
    print("Unexpected error: \(error).")
}
wrappedUname.waitUntilExit()
let unameOutput = String(decoding: unameOutputPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
let unameError = String(decoding: unameOutputPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
print("Output: " + unameOutput)
print("Error: " + unameError)
Continue reading