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

时间:2018-10-12 20:14:53

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

我正在迅速编写一个macOS命令行工具来执行shell命令:

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

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

如果我的程序意外终止,是否可以自动终止它们?

1 个答案:

答案 0 :(得分:0)

这是我们在使用两个管道子进程时对中断(CTRL-C)做出反应的方法。

后面的想法:阻止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 **