Playground runs indefinitely when trying to execute a binary

Hi all!
I've got a silly question. I'm working on making a simple Swift library to serve as a static site generator. It's going to use the Typst binary to take .typ files and transform them to .html files. I've tried to cobble together the following code as a test, but when running it in a playground it just stays at running and never returns any result.

import Foundation

let task = Process()
let outputPipe = Pipe()
let errorPipe = Pipe()
task.standardOutput = outputPipe
task.standardError = errorPipe
task.executableURL = URL(fileURLWithPath: "~/documents/development/typst-aarch64-apple-darwin/typst")
let fileName = "~/documents/development/typst-aarch64-apple-darwin/MetaTest.typ"
task.arguments = ["compile", "--features", "html", "--format", "html", fileName, "-"]
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
let output = String(decoding: outputData, as: UTF8.self)
let error = String(decoding: errorData, as: UTF8.self)
try task.run()
print(output)
print(error)

The playground gives me this information, but I really can't figure out what it means or what the program is hanging on.

task : <NSConcreteTask: 0x6000020589b0>
class NSConcreteTask
super
class NSTask

Thanks for any help!

it looks like let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile will block indefinitely waiting for the output pipe to close, but it will never close because you never get to try task.run()

1 Like

If you want to spawn child processes, I strongly recommend that you use the the shiny new Subprocess package rather than working with Process directly.

If you can’t use that for some reason, there are a variety of other wrappers you could use. You can find my one on DevForums: Running a Child Process with Standard Input and Output.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

4 Likes

Ahhhh I see now, thanks for pointing that out and sorry, I'm very new to writing Swift. I'm a chemical engineer by training.

Ah this looks much nicer than Process! I'll give Subprocess a try thanks for the tip!

1 Like