Created
October 8, 2018 20:24
-
-
Save bugaevc/4307eaf045e4b4264d8e395b5878a63b to your computer and use it in GitHub Desktop.
Calling fork() from 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
// Note: calling fork() can be unsafe and dangerous, that | |
// is why Swift doesn't let you invoke it directy. Be very | |
// careful about how you use fork(). For some more details, | |
// see https://www.evanjones.ca/fork-is-dangerous.html and | |
// http://www.sealiesoftware.com/blog/archive/2017/6/5/Objective-C_and_fork_in_macOS_1013.html | |
import Darwin | |
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) | |
let forkPtr = dlsym(RTLD_DEFAULT, "fork") | |
typealias ForkType = @convention(c) () -> Int32 | |
let fork = unsafeBitCast(forkPtr, to: ForkType.self) | |
switch fork() { | |
case -1: | |
print("Error") | |
case 0: | |
print("Child") | |
default: | |
print("Parent") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment