Swift: command line tool exit callback

2019-08-17 16:54发布

I need to know when a command line program is stopped by the user to release some active bluetooth connections from a command-line program (running on the terminal), written in swift.

Say the user calls the program then exits by pressing ctrl+Z. How would I know ?

1条回答
时光不老,我们不散
2楼-- · 2019-08-17 17:35

You can install a signal handler with Swift. For example:

import Foundation

let startTime = Date()
var signalReceived: sig_atomic_t = 0

signal(SIGINT) { signal in signalReceived = 1 }

var i = 0
while true {
    if signalReceived == 1 { break }
    usleep(500_000)
    if signalReceived == 1 { break }
    i += 1
    print(i)
}

let endTime = Date()
print("Program has run for \(endTime.timeIntervalSince(startTime)) seconds")

Modified from this gist.

查看更多
登录 后发表回答