swift - 在 Swift 中终止 macOS 命令行工具的子进程

标签 swift shell command-line-interface command-line-tool

我正在用 swift 编写一个 macOS 命令行工具,它执行 shell 命令:

let process = Process()
process.launchPath = "/bin/sleep"
process.arguments = ["100"]
process.launch()
process.waitUntilExit()

但是,如果中断 (CTRL-C) 或终止信号发送到我的程序,这些 shell 命令不会终止,而是继续执行。

如果我的程序意外终止,有没有办法自动终止它们?

最佳答案

以下是我们在使用两个管道子进程时对中断 (CTRL-C) 使用react所做的操作。

背后的想法:阻塞waitUntilExit()调用替换为异步terminationHandler。无限循环 dispatchMain() 用于服务调度事件。收到 Interrupt 信号后,我们在子进程上调用 interrupt()

封装子进程启动和中断逻辑的示例类:

class AppTester: Builder {

   private var processes: [Process] = [] // Keeps references to launched processes.

   func test(completion: @escaping (Int32) -> Void) {

      let xcodebuildProcess = Process(executableName: "xcodebuild", arguments: ...)
      let xcprettyProcess = Process(executableName: "xcpretty", arguments: ...)

      // Organising pipe between processes. Like `xcodebuild ... | xcpretty` in shell
      let pipe = Pipe()
      xcodebuildProcess.standardOutput = pipe
      xcprettyProcess.standardInput = pipe

      // Assigning `terminationHandler` for needed subprocess.
      processes.append(xcodebuildProcess)
      xcodebuildProcess.terminationHandler = { process in
         completion(process.terminationStatus)
      }

      xcodebuildProcess.launch()
      xcprettyProcess.launch()
      // Note. We should not use blocking `waitUntilExit()` call.
   }

   func interrupt() {
      // Interrupting running processes (if any).
      processes.filter { $0.isRunning }.forEach { $0.interrupt() }
   }
}

用法(即main.swift):

let tester = AppTester(...)
tester.test(....) {
   if $0 == EXIT_SUCCESS {
      // Do some other work.
   } else {
      exit($0)
   }
}

// Making Interrupt signal listener.
let source = DispatchSource.makeSignalSource(signal: SIGINT)
source.setEventHandler {
   tester.interrupt() // Will interrupt running processes (if any).
   exit(SIGINT)
}
source.resume()
dispatchMain() // Starting dispatch loop. This function never returns.

shell 中的输出示例:

...
▸ Running script 'Run Script: Verify Sources'
▸ Processing Framework-Info.plist
▸ Running script 'Run Script: Verify Sources'
▸ Linking AppTestability
^C** BUILD INTERRUPTED **

关于swift - 在 Swift 中终止 macOS 命令行工具的子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786443/

相关文章:

shell - 主机上的 Vagrant 供应

ruby - 如何创建支持 Ruby 的 shell 命令?

php - ssh 连接虽然 ssh2_connect 失败

vue.js - 找不到模块 '@/assets/<file-name-here>.svg'。 @vue/cli 版本 : 4. 2.3 和 4.3.1

amazon-web-services - aws eb cli 3 为错误的帐户设置应用程序

ios - 调度组通知不起作用

swift - 如何在 AppDelegate 和 ViewController 之间共享属性,并在 App 终止之前保存

ios - 从 TableView 中选择时在多个详细 View 之间切换

IOS Swift 如何将搜索功能包含在另一个功能中

Python Click - 从配置文件提供参数和选项