Last active
May 5, 2024 12:55
-
-
Save dduan/d4e967f3fc2801d3736b726cd34446bc to your computer and use it in GitHub Desktop.
How to fork()+execv() in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment