【问题标题】:NSTask : Couldn't posix_spawn: error 13 when launching appNSTask:无法 posix_spawn:启动应用程序时出现错误 13
【发布时间】:2016-11-03 02:36:52
【问题描述】:

我的主 Swift 应用中有一个子应用。我做了它,因此在构建它时它会自动复制到主应用程序的 Resources 文件夹中。这样,我希望能够从主应用程序启动子应用程序的实例。

问题是,我遇到了一个难以调试/找到答案的错误。

这是我的代码:

    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 选项设置为 no。 该子应用需要在后台做一些工作,根本不需要任何 UI。

谢谢!

【问题讨论】:

  • Error 13Permission Denied 的错误。你的helperPath 是什么?如果不是/usr/bin,就会报这个错误。

标签: xcode swift macos nstask


【解决方案1】:

不要为此使用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() 方法。

【讨论】:

  • 这工作正常,谢谢。但我不确定它是否与我需要做的兼容。我需要能够启动应用程序助手的多个实例(我相信这没问题),并以编程方式终止给定的一个。任务确实有一个terminate() 方法。我可以用openURL() 做同样的事情吗?
  • 是的,你应该可以用openURL(_:options:configuration:) 做类似的事情。正在更新答案...
【解决方案2】:

launch() 函数已弃用,使用 run()

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")

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 2013-10-27
    • 2013-11-20
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2023-03-27
    相关资源
    最近更新 更多