在 Swift 命令行应用程序中捕获信号 [英] Trapping signals in a Swift command line application
本文介绍了在 Swift 命令行应用程序中捕获信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Swift 中正确捕获 SIGINT
和 SIGTERM
等不同信号?例如,当人们通过按 Control-C 停止我的脚本时,我想在终止它之前做一些清理.
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.
推荐答案
调度源可用于监视 UNIX 信号.
Dispatch Sources can be used to monitor UNIX signals.
这是一个简单的例子,一个 Swift 3 中 C 代码的翻译监控信号"部分来自并发编程指南.
Here is a simple example, a Swift 3 translation of the C code in the "Monitoring Signals" section from the Concurrency Programming Guide.
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()
请注意,这需要一个活动的 GCD 事件循环,例如与
Note that this requires an active GCD event loop, e.g. with
dispatchMain()
在命令行程序中.
这篇关于在 Swift 命令行应用程序中捕获信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文