0

I'm trying to use NSTask (or Process since this is Swift) to execute xmllint to format some XML data. The problem is that the task seems to hang.

I'm using xmllint rather than XMLDocument.xmlData(withOptions:) because the output better matches what I need. I'm writing a tool to edit existing files and I want to minimize the impact.

I tried killing the xmllint process while it was hung, and got the first 84 1/2 lines of the output. The output should be about 10,000 lines for that test case, and most of the content involves elements nested only a couple of levels so it's not a very complex task.

Am I setting up the process and pipes correctly? The documentation is vague and I had a hard time finding directly applicable examples.

The code:

  public static func format(xml: XMLDocument) -> Data?
  {
    let data = xml.xmlData
    let task = Process()
    let inPipe = Pipe()
    let outPipe = Pipe()


    task.launchPath = "/usr/bin/xmllint"
    task.arguments = ["--format", "-"]
    task.standardInput = inPipe
    task.standardOutput = outPipe
    task.launch()
    inPipe.fileHandleForWriting.write(data)
    inPipe.fileHandleForWriting.closeFile()
    task.waitUntilExit()  // Hangs :(
    return outPipe.fileHandleForReading.availableData
  }
Uncommon
  • 3,323
  • 2
  • 18
  • 36
  • 2
    It could be the same issue as in [cURL through NSTask not terminating if a pipe is present](http://stackoverflow.com/questions/36009175/curl-through-nstask-not-terminating-if-a-pipe-is-present) – try reading *before* waiting for process exit. – Martin R May 15 '17 at 17:54
  • That did it! Thanks! – Uncommon May 15 '17 at 18:02

0 Answers0