I'm writing a macOS command line tool in swift which executes shell commands:
let process = Process()
process.launchPath = "/bin/sleep"
process.arguments = ["100"]
process.launch()
process.waitUntilExit()
However, if an interrupt (CTRL-C
) or a terminate signal gets sent to my program, these shell commands don't get terminated and just continue with their execution.
Is there a way to automatically terminate them if my program gets terminated unexpectedly?
Here is what we did in order to react on interrupt (
CTRL-C
) when using two piped subprocesses.Idea behind: Blocking
waitUntilExit()
call replaced with asyncterminationHandler
. Infinite loopdispatchMain()
used to serve dispatch events. On receivingInterrupt
signal we callinginterrupt()
on subprocesses.Example class which incapsulates subprocess launch and interrupt logic:
Usage (i.e.
main.swift
):Example output in shell: