Created
November 23, 2015 03:46
-
-
Save sharplet/d640eea5b6c99605ac79 to your computer and use it in GitHub Desktop.
Simple signal handling 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 Darwin | |
enum Signal: Int32 { | |
case HUP = 1 | |
case INT = 2 | |
case QUIT = 3 | |
case ABRT = 6 | |
case KILL = 9 | |
case ALRM = 14 | |
case TERM = 15 | |
} | |
func trap(signal: Signal, action: @convention(c) Int32 -> ()) { | |
// From Swift, sigaction.init() collides with the Darwin.sigaction() function. | |
// This local typealias allows us to disambiguate them. | |
typealias SignalAction = sigaction | |
var signalAction = SignalAction(__sigaction_u: unsafeBitCast(action, __sigaction_u.self), sa_mask: 0, sa_flags: 0) | |
withUnsafePointer(&signalAction) { actionPointer in | |
sigaction(signal.rawValue, actionPointer, nil) | |
} | |
} | |
trap(.INT) { signal in | |
print("intercepted signal \(signal") | |
} | |
print("going to sleep...") | |
sigsuspend(nil) |
@bwahacker it is documented .
FWIW, this is not needed anymore in Swift 3. You can directly call:
signal(SIGINT) { s in print("signal") }
from anywhere. :)
The fact that you have to go around the internet looking for something as simple as this is impressive. THANK YOU. You're the one one that show that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Frizlab Thanks a ton for that snippet; I don't think I would have ever found the solution for Swift 3!