Skip to content

Instantly share code, notes, and snippets.

@Danappelxx
Last active April 6, 2020 01:50
Show Gist options
  • Save Danappelxx/716da056cf11b1adc505 to your computer and use it in GitHub Desktop.
Save Danappelxx/716da056cf11b1adc505 to your computer and use it in GitHub Desktop.
import Darwin.C
import Venice
struct SubProcess {
let path: String
let arguments: [String]
func run(sync sync: Bool = true) -> Int? {
let childPID = fork()
switch childPID {
case -1: // error
return nil
case 0: // child
let executable = path.characters.split("/").last?.map { String($0) }.joinWithSeparator("") ?? ""
let args = ([executable] + arguments).map { $0.withCString(strdup) } + [nil] // null terminated
execv(path, args)
fatalError("The execv function failed and did not overwrite child process's memory successfully. (errno: \(errno))")
default: // parent
if sync { waitpid(childPID, nil, 0) } // blocks until child exits
else { signal(SIGCHLD, SIG_IGN) } // ignore child signal
return Int(childPID)
}
}
}
let sp = SubProcess(path: "/bin/echo", arguments: ["hello", "world"])
// launch 3 child processes (which prints "hello world" 3 times)
for i in 1...3 {
sp.run(sync: false)
print("launched \(i)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment