Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created January 12, 2016 23:00
Show Gist options
  • Save kristopherjohnson/1246d909462fb31dc800 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/1246d909462fb31dc800 to your computer and use it in GitHub Desktop.
Demonstrate launching an `NSTask` and asynchronously reading its output.
import Cocoa
/// Demonstrate launching an `NSTask` and asynchronously reading its output.
///
/// Credit: <http://stackoverflow.com/a/23938137/1175>
func testTaskOutputPipe() {
let task = NSTask()
task.launchPath = "/bin/ls"
task.arguments = ["-l", "/Applications"]
let stdoutPipe = NSPipe()
task.standardOutput = stdoutPipe
let stdoutHandle = stdoutPipe.fileHandleForReading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
var data = stdoutHandle.availableData
while data.length > 0 {
if let s = NSString(data: data, encoding: NSUTF8StringEncoding) {
print(s, terminator: "")
data = stdoutHandle.availableData
}
}
}
task.launch()
task.waitUntilExit()
}
testTaskOutputPipe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment