Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@ehsan9891

This comment has been minimized.

Copy link

commented May 14, 2016

how can i use it in a project? print is not allowed to use in root

@dedeexe

This comment has been minimized.

Copy link

commented Nov 3, 2016

@ehsan9891. Try use it to output the result in a file. I use signals to manipulate the process via terminal.
In my case I use SIGINT to generate performance report.

E.g:
$ kill -s SIGINT

@Frizlab

This comment has been minimized.

Copy link

commented Feb 11, 2017

FWIW, this is not needed anymore in Swift 3. You can directly call:

signal(SIGINT) { s in print("signal") }

from anywhere.
:)

@bwahacker

This comment has been minimized.

Copy link

commented Jun 7, 2017

@Frizlab Thanks a ton for that snippet; I don't think I would have ever found the solution for Swift 3!

@namper

This comment has been minimized.

Copy link

commented Jul 12, 2017

@bwahacker it is documented .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.