可可应用程序崩溃时如何终止进程或nstask

时间:2019-04-14 04:24:22

标签: swift macos

当应用程序崩溃或被kill -9 pid命令杀死时,如何终止应用程序启动的进程

我正在编写一个macos gui应用程序,它将启动Redis服务器。我正在使用Process运行redis服务器。但是,当应用程序崩溃或被命令杀死时,由应用程序启动的Process不会终止。

import Cocoa
import Foundation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var task = Process()
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // start the redis-server

        let bundlePath = Bundle.main.bundlePath
        let redisServerPath = bundlePath.appending("/Contents/Resources/redis-server")
        let redisConfigPath = bundlePath.appending("/Contents/Resources/redis.conf")
        print(Bundle.main.bundlePath.appending("/Contents/Resources/redis-server"))
        if #available(OSX 10.13, *) {
            task.executableURL = URL(fileURLWithPath:redisServerPath)
        } else {
            task.launchPath = redisServerPath
        }
        task.arguments = [redisConfigPath]
        print(getpid())
        if #available(OSX 10.13, *) {
            do {
                try  task.run()
            } catch {
                print("\(error)")
            }

        } else {
            task.launch()
        }
        print(task.processIdentifier)
        processId = task.processIdentifier
    }
    func applicationWillTerminate(_ aNotification: Notification) {
        // when the application stop normally ,this func will trigger,but when crash or kill by command, this fucn will never trigger
        print("closing")
        task.terminate()
        task.waitUntilExit()
    }
}

因此,有一种方法可以在主应用程序崩溃或被命令杀死时杀死子进程。

0 个答案:

没有答案