Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Guang1234567
Forked from sharplet/trap.swift
Created August 25, 2021 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Guang1234567/913cfbb0855fba9953a469a4c5be06d4 to your computer and use it in GitHub Desktop.
Save Guang1234567/913cfbb0855fba9953a469a4c5be06d4 to your computer and use it in GitHub Desktop.
Simple signal handling in Swift
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment