From bc22272573665f18d2ff92ef36d7847e8f64c9d4 Mon Sep 17 00:00:00 2001 From: Claudio Cambra Date: Thu, 19 Sep 2024 20:10:46 +0800 Subject: [PATCH] Correctly kill processes spawned by mac-crafter if mac-crafter quits/is killed/etc Signed-off-by: Claudio Cambra --- .../osx/mac-crafter/Sources/Utils/Shell.swift | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/admin/osx/mac-crafter/Sources/Utils/Shell.swift b/admin/osx/mac-crafter/Sources/Utils/Shell.swift index a240ccffa51c2..1d7a35522c411 100644 --- a/admin/osx/mac-crafter/Sources/Utils/Shell.swift +++ b/admin/osx/mac-crafter/Sources/Utils/Shell.swift @@ -14,6 +14,8 @@ import Foundation +var task: Process? + @discardableResult func run( _ launchPath: String, @@ -21,24 +23,31 @@ func run( env: [String: String]? = nil, quiet: Bool = false ) -> Int32 { - let task = Process() - task.launchPath = launchPath - task.arguments = args + defer { task = nil } + task = Process() + + signal(SIGINT) { _ in + task?.terminate() // Send terminate signal to the task + exit(0) // Exit the script after cleanup + } + + task?.launchPath = launchPath + task?.arguments = args if let env, - let combinedEnv = task.environment?.merging(env, uniquingKeysWith: { (_, new) in new }) + let combinedEnv = task?.environment?.merging(env, uniquingKeysWith: { (_, new) in new }) { - task.environment = combinedEnv + task?.environment = combinedEnv } if quiet { - task.standardOutput = nil - task.standardError = nil + task?.standardOutput = nil + task?.standardError = nil } - task.launch() - task.waitUntilExit() - return task.terminationStatus + task?.launch() + task?.waitUntilExit() + return task?.terminationStatus ?? 1 } func run(