NSTask:无法posix_spawn:启动应用程序时出现错误13



我在我的主要Swift应用中具有子应用。我做到了,因此在构建主应用程序的资源文件夹中会自动复制它。这样,我希望能够从主应用程序启动sub-app实例。

事实是,我的错误很难调试/查找有关的答案。

这是我的代码:

    let args = ["--args", "-admin_url", site.url, "-login", site.login, "-pass", site.password]
    let helperPath = (NSBundle.mainBundle().pathForResource("App Helper", ofType: "app"))!
    let task = NSTask.init()
    task.launchPath = helperPath
    task.arguments = args
    task.launch()

和错误:

[56490:7218926] Couldn't posix_spawn: error 13

我不知道在哪里看,要寻找什么。我不知道我在做什么错。我想知道问题是否与亚应用程序本身有关。该亚应用程序目前为空。我将Application is Agent设置为YES。在mainmenu.xib中,我将Visible at launch选项设置为否。该子应用需要在后台做一些工作,并且根本不需要任何UI。

谢谢!

不要为此使用NSTask,请使用NSWorkspace

let helperAppURL = NSBundle.mainBundle().URLForResource("App Helper",
                                      withExtension:"app")!
_ = try? NSWorkspace.sharedWorkspace().openURL(helperAppURL,
       options:[.Default],
   configuration:[NSWorkspaceLaunchConfigurationArguments :
            ["--args", "-admin_url", site.url, "-login",
             site.login, "-pass", site.password]])

在上面的代码中,对于简洁起见,我忽略了openURL()命令的结果,但实际上它可以返回代表任务的NSRunningApplication实例。

要跟踪您启动的辅助应用程序的实例,您可以在适当的收集类中保留对此NSRunningApplication的引用,当时间到来时,请致电其terminate()方法。

使用 run()

不建议使用launch()功能
func shell(_ command: String) -> String {
  let task = Process()
  task.launchPath = "/usr/bin/"
  task.arguments = ["-c", command]
  
  let pipe = Pipe()
  task.standardOutput = pipe
  
  if #available(macOS 10.13, *) {
    try? task.run()
  } else {
    task.launch()
  }
  
  let data = pipe.fileHandleForReading.readDataToEndOfFile()
  let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
  
  return output
}

或使用swift-commands

import Commands
Commands.Bash.run("say hello")

相关内容

最新更新