[英]How to create a minimal daemon process in a swift 2 command line tool?
我想运行一个守护进程,它可以在command line tool
xcode 项目中监听 OSX 系统事件,比如NSWorkspaceWillLaunchApplicationNotification
? 那可能吗? 如果没有,为什么不呢,是否有任何变通方法或黑客?
以下来自swift 2
cocoa application
项目的示例代码设置了一个系统事件侦听器,它WillLaunchApp
每次 OSX 应用程序启动时调用WillLaunchApp
。 (这工作得很好)
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
print(notification)
}
}
相比之下,这个类似的swift 2
command line tool
项目不会调用WillLaunchApp
。
import Cocoa
class MyObserver: NSObject
{
override init() {
super.init()
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
// is never called
print(notification)
}
}
let observer = MyObserver()
while true {
// simply to keep the command line tool alive - as a daemon process
sleep(1)
}
我猜我在这里遗漏了一些cocoa
和/或xcode
基础知识,但我无法弄清楚是哪些。 也许它与 while-true 循环有关,它可能会阻止事件。 如果是这样,是否有正确的方法来运行守护进程?
事实证明,使用while true
循环确实会阻塞主线程。 简单地用NSRunLoop.mainRunLoop().run()
替换while true
循环,你就有了一个守护进程。
我阅读了swifter (一个基于 swift 的服务器)的来源,它也在做同样的事情。
在 Swift 3 及更高版本中,等效代码为:
RunLoop.main.run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.