Trapping signals in a Swift command line application

Viewed 3297

How to capture different signals such as SIGINT and SIGTERM in Swift correctly? For example, when people stop my script by pressing Control-C, I want to do some cleanup before terminating it.

2 Answers

I use a simpler approach. Just past those lines before any code is executed in the main.swift:

let signalCallback: sig_t = { signal in
    NSLog("Got signal: \(signal)")
    exit(signal)
}

signal(SIGINT, signalCallback)

There is a limitation though. You can only access global-scoped things from the signalCallback.

Related