[swift-users] GCD and Process

Mr Bee pak.lebah at yahoo.com
Fri Jan 6 01:39:13 CST 2017


Hi all,
I'm currently still learning Swift 3. Now I'm playing around with GCD (grand central dispatch). I'd like to start an external process using Process from an asynced thread, and create another thread to stop that external process after some times. Here's what I do…
import Foundationimport Dispatch
extension Process {  func execute(command: String, currentDir: String = "~", arguments: [String] = [], input: String = "") -> String {    if !input.isEmpty {      let pipeIn = Pipe()      self.standardInput = pipeIn      // multiple inputs are separated by newline      if let input = input.data(using: String.Encoding.utf8) {        pipeIn.fileHandleForWriting.write(input)      }    }        let pipeOut = Pipe()    self.standardOutput = pipeOut        self.arguments = arguments    self.launchPath = command    self.currentDirectoryPath = currentDir        self.launch()    let output = pipeOut.fileHandleForReading.readDataToEndOfFile()    self.waitUntilExit()        return String(data: output, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!  }}
//print(Process().execute(command: "/bin/ls", arguments: ["-l"]))
var cmd = Process()
print("Starting...")
DispatchQueue.global(qos: .default).async {  print("Executing...")  let s = cmd.execute(command: "/bin/ls", arguments: ["-l"])  print(s)}
DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + .seconds(5)) {  if cmd.isRunning {    print("Terminating...")    cmd.terminate()  }}
print("Done.") 
The code doesn't work as expected. The execute() function itself works fine (uncomment the call in the middle of the code), but I don't know why it doesn't work if it's called from within DispatchQueue closure. Even if I call a much more simple function —like a for loop— it doesn't work consistenly, sometimes the loop is completed, but other times it's not.
Google didn't really help me because this topic is pretty rare I suppose. Could anyone enlight me, how to make the code works as I expected? What did I do wrong?
Thank you.
Regards,

–Mr Bee
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170106/3e7520c1/attachment.html>


More information about the swift-users mailing list