2命令行工具中创建最小的守护进程

2命令行工具中创建最小的守护进程

本文介绍了如何在swift 2命令行工具中创建最小的守护进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个守护进程,可以监听OSX系统事件,例如 NSWorkspaceWillLaunchApplicationNotification 命令行工具 xcode项目?那可能吗?

I want to run a daemon process that can listen to OSX system events like NSWorkspaceWillLaunchApplicationNotification in an command line tool xcode project? Is that possible? And if not, why not and are there any work arounds or hacks?

以下来自 swift 2 可可应用程序的示例代码设置了一个系统事件侦听器,它调用 WillLaunchApp 每次启动OSX应用程序。 ( this works just fine

The following sample code from a swift 2 cocoa application project sets up a system event listener, which calls WillLaunchApp every time an OSX app gets started. (this works just fine)

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 命令行工具项目不会调用 WillLaunchApp

In contrast this simingly similar swift 2 command line tool project will not call 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循环相关,这可能阻塞事件。

I am guessing I am missing some cocoa and/or xcode fundamentals here, but I cannot figure out which ones. Maybe it is related to the while-true loop, which might be blocking the events. If so, is there a correct way to run a daemon process?

推荐答案

是否有正确的方法来运行

结果是使用而true loop会阻塞主线程。
只需使用 NSRunLoop.mainRunLoop()。run()替换 while 循环, daemon进程。

It turns out using while true loop does block the main-thread.Simply replace the while true loop with NSRunLoop.mainRunLoop().run() and you have a daemon process.

我阅读了 swifter (一个基于swift的服务器),这是做同样的。

I read the sources of swifter (a swift-based server), which is doing the same.

这篇关于如何在swift 2命令行工具中创建最小的守护进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:19