Skip to content

Instantly share code, notes, and snippets.

@sharplet
Created November 23, 2015 03:46
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sharplet/d640eea5b6c99605ac79 to your computer and use it in GitHub Desktop.
Save sharplet/d640eea5b6c99605ac79 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)
@ehsan9891
Copy link

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

@dedeexe
Copy link

dedeexe 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
Copy link

Frizlab 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
Copy link

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

@namper
Copy link

namper commented Jul 12, 2017

@bwahacker it is documented .

@ConsoleTVs
Copy link

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