Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- func withCStrings(_ strings: [String], scoped: ([UnsafeMutablePointer<CChar>?]) throws -> Void) rethrows {
- let cStrings = strings.map { strdup($0) }
- try scoped(cStrings + [nil])
- cStrings.forEach { free($0) }
- }
- enum RunCommandError: Error {
- case WaitPIDError
- case POSIXSpawnError(Int32)
- }
- func runCommand(_ command: String, completion: ((Int32) -> Void)? = nil) throws {
- var pid: pid_t = 0
- let args = ["sh", "-c", command]
- let envs = ProcessInfo().environment.map { k, v in "\(k)=\(v)" }
- try withCStrings(args) { cArgs in
- try withCStrings(envs) { cEnvs in
- var status = posix_spawn(&pid, "/bin/sh", nil, nil, cArgs, cEnvs)
- if status == 0 {
- if (waitpid(pid, &status, 0) != -1) {
- completion?(status)
- } else {
- throw RunCommandError.WaitPIDError
- }
- } else {
- throw RunCommandError.POSIXSpawnError(status)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement