Doug Doug - 1 year ago 96
Swift Question

How do I replace the current Swift script process with a different one

When using Ruby, the following will terminate the current ruby script and replace the process with an instance of ssh:

exec "ssh host -p 1234 -v"

Is this possible to do in Swift?

Answer Source

execv and related functions from the BSD library can be called from Swift (with the exception of those with a variable argument list). The only "challenge" is to create a


that can be passed as the argument list. A simple example:

import Foundation

let args = ["ls", "-l", "/Library"]

// Array of UnsafeMutablePointer<Int8>
let cargs = { strdup($0) } + [nil]

execv("/bin/ls", cargs)

fatalError("exec failed")

Here it is used that you can pass a Swift string to the C function strdup() which expects a const char *, and the compiler creates a temporary UTF-8 representation (see String value to UnsafePointer<UInt8> function parameter behavior).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download