如何捕捉到不同的信号,如SIGINT和SIGTERM斯威夫特是否正确?例如,当人们通过按Control- 停止我的脚本时C,我想在终止之前进行一些清理.
Mar*_*n R 11
Dispatch Sources 可用于监控UNIX信号.
这是一个简单的例子,来自并发编程指南的"监控信号"部分中的C代码的Swift 3转换 .
import Dispatch // or Foundation
signal(SIGINT, SIG_IGN) // // Make sure the signal does not terminate the application.
let sigintSrc = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
sigintSrc.setEventHandler {
print("Got SIGINT")
// ...
exit(0)
}
sigintSrc.resume()
Run Code Online (Sandbox Code Playgroud)
请注意,这需要一个活动的GCD事件循环,例如
dispatchMain()
Run Code Online (Sandbox Code Playgroud)
在命令行程序中.