Created
November 29, 2022 21:22
-
-
Save jbadger3/a471418b47e63478e9432c5341a3f3ef to your computer and use it in GitHub Desktop.
Demo using readabilityHandler to read data asynchronously from FileHandle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let outputPipe = Pipe() | |
let process = Process() | |
process.executableURL = URL(fileURLWithPath:"/bin/bash") | |
process.arguments = ["-c", "ls"] | |
process.standardOutput = outputPipe | |
outputPipe.fileHandleForReading.readabilityHandler = { fileHandle in | |
print("handler called") | |
let data = fileHandle.availableData | |
if data.isEmpty { | |
outputPipe.fileHandleForReading.readabilityHandler = nil | |
return | |
} | |
if let outputString = String(data: data, encoding: .utf8) { | |
print(outputString) | |
} | |
} | |
try? process.run() | |
let standardInputFH = process.standardInput as! FileHandle | |
let standardErrorFH = process.standardError as! FileHandle | |
print("PID: \(process.processIdentifier)") | |
print("stdin FD: \(standardInputFH.fileDescriptor)") | |
print("stdout FD: \(outputPipe.fileHandleForReading.fileDescriptor)") | |
print("stderr FD: \(standardErrorFH.fileDescriptor)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment