Skip to content

Instantly share code, notes, and snippets.

@RLovelett
Created April 21, 2016 02:22
Show Gist options
  • Save RLovelett/f70e3beb86a81d8ed363834e9f104d93 to your computer and use it in GitHub Desktop.
Save RLovelett/f70e3beb86a81d8ed363834e9f104d93 to your computer and use it in GitHub Desktop.
Spawn a sub-process from Swift
import Glibc
var action = posix_spawn_file_actions_t()
posix_spawn_file_actions_init(&action);
defer { posix_spawn_file_actions_destroy(&action) }
posix_spawn_file_actions_addopen(&action, 1, "/tmp/foo-log", (O_WRONLY | O_CREAT | O_TRUNC), 0644)
posix_spawn_file_actions_adddup2(&action, 1, 2)
let args = [
"ffmpeg",
"-version"
]
let argv: [UnsafeMutablePointer<CChar>?] = args.map{ $0.withCString(strdup) }
defer { for case let arg? in argv { free(arg) } }
var pid = pid_t()
let rv = posix_spawnp(&pid, argv[0], &action, nil, argv + [nil], nil)
guard rv == 0 else {
// Should get errno
exit(1)
}
print(pid)
var exitCode: Int32 = 0
waitpid(pid, &exitCode, 0)
print("Process exited with code \(exitCode)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment