【问题标题】:How to create a minimal daemon process in a swift 2 command line tool?如何在 swift 2 命令行工具中创建最小的守护进程?
【发布时间】:2015-10-06 19:17:01
【问题描述】:

我想做什么

我想在command line tool xcode 项目中运行一个可以侦听诸如NSWorkspaceWillLaunchApplicationNotification 之类的OSX 系统事件的守护进程?那可能吗?如果没有,为什么不呢?是否有任何解决方法或技巧?

一些代码示例

来自swift 2cocoa application 项目的以下示例代码设置了一个系统事件侦听器,每次启动 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 2command 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 循环有关,它可能会阻塞事件。如果是这样,是否有正确方法来运行守护进程进程?

【问题讨论】:

    标签: xcode macos swift cocoa swift2


    【解决方案1】:

    原来使用while true 循环确实阻塞了主线程。 只需将while true 循环替换为NSRunLoop.mainRunLoop().run(),您就有了一个守护进程。

    我阅读了swifter(基于 swift 的服务器)的源代码,它也在做同样的事情。

    【讨论】:

      【解决方案2】:

      在 Swift 3 及更高版本中,等效代码为:

      RunLoop.main.run()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        • 2020-10-29
        • 2015-11-09
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        相关资源
        最近更新 更多