Post not yet marked as solved
Post marked as unsolved with 1 replies, 213 views
I refer to this article:
https://developer.apple.com/forums/thread/129752
extension Cmd {
static func launch(tool: URL, arguments: [String], completionHandler: @escaping (Int32, Data) -> Void) throws {
let group = DispatchGroup()
let pipe = Pipe()
var standardOutData = Data()
group.enter()
let proc = Process()
proc.executableURL = tool
proc.arguments = arguments
proc.standardOutput = pipe.fileHandleForWriting
proc.terminationHandler = { _ in
proc.terminationHandler = nil
group.leave()
}
group.enter()
DispatchQueue.global().async {
// Doing long-running synchronous I/O on a global concurrent queue block
// is less than ideal, but I’ve convinced myself that it’s acceptable
// given the target ‘market’ for this code.
let data = pipe.fileHandleForReading.readDataToEndOfFile()
pipe.fileHandleForReading.closeFile()
DispatchQueue.main.async {
standardOutData = data
group.leave()
}
}
group.notify(queue: .main) {
completionHandler(proc.terminationStatus, standardOutData)
}
try proc.run()
// We have to close our reference to the write side of the pipe so that the
// termination of the child process triggers EOF on the read side.
pipe.fileHandleForWriting.closeFile()
}
}
run shell :
try Cmd.launch(tool: URL(fileURLWithPath: "/usr/bin/which"), arguments: ["docker"]) { (status, outputData) in
let output = String(data: outputData, encoding: .utf8) ?? ""
print("done, status: \(status), output: \(output)")
}
the result print:
done, status: 1, output:
i had remove sandbox and use this code in my mac app. and return value is empty string.
I tried running this script using https://github.com/kareman/SwiftShell and got the same result