Skip to content

Instantly share code, notes, and snippets.

@jakubpetrik
Created September 23, 2015 21:34
Show Gist options
  • Save jakubpetrik/8fe8b1b6c5829d8ca94a to your computer and use it in GitHub Desktop.
Save jakubpetrik/8fe8b1b6c5829d8ca94a to your computer and use it in GitHub Desktop.
Signal handling in Swift
/**
http://rosettacode.org/wiki/Handle_a_signal
Most general purpose operating systems provide interrupt facilities, sometimes called signals.
Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are
created so that the program behaves in a well-defined manner upon receipt of a signal.
For this task you will provide a program that displays a single integer on each line of output at
the rate of one integer in each half second. Upon receipt of the SigInt signal (often created by the user typing ctrl-C)
the program will cease printing integers to its output, print the number of seconds the program has run,
and then the program will terminate.
*/
import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
@DG12
Copy link

DG12 commented Apr 30, 2017

Setting a flag and testing it within the "for" of the program is not a good way to use trap.

If the code in the for is in a loop, it will never come out to encounter the break

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment