Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Last active January 8, 2020 03:03
Show Gist options
  • Save dedeexe/67e0fe0e7263d44309ba705e3054eb0d to your computer and use it in GitHub Desktop.
Save dedeexe/67e0fe0e7263d44309ba705e3054eb0d to your computer and use it in GitHub Desktop.
How to trap OS signals using swift
enum SignalTrap {
typealias SignalHandler = @convention(c)(Int32) -> Void
static func handle(signal:Int32, action: @escaping SignalHandler) {
typealias SignalAction = sigaction
var sigAction = sigaction()
sigAction.__sigaction_u = unsafeBitCast(action, to: __sigaction_u.self)
sigaction(signal, &sigAction, nil)
}
}
// ---------------------------------------------------------
// Usage
SignalTrap.handle(signal: SIGHUP) { value in
print("Signal value: \(value)")
}
// ---------------------------------------------------------
// Testing
// # Run command
// $ ps -ax MyApp
//
// # Get result similar to
// 12345 ttys000 0:00.01 MyApp
//
// # Send signal to process
// $ kill -HUP 12345
// ---------------------------------------------------------
// References
// * $ man sigaction - sigaction manual
// * https://dev.iachieved.it/iachievedit/trapping-signals-with-swift-on-linux/
// * https://github.com/alexito4/Trap/blob/master/Sources/Trap.swift
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment