Correctly kill processes spawned by mac-crafter if mac-crafter quits/is killed/etc
authorClaudio Cambra <claudio.cambra@nextcloud.com>
Thu, 19 Sep 2024 12:10:46 +0000 (20:10 +0800)
committerbackportbot[bot] <backportbot[bot]@users.noreply.github.com>
Mon, 23 Sep 2024 08:37:36 +0000 (08:37 +0000)
Signed-off-by: Claudio Cambra <claudio.cambra@nextcloud.com>
admin/osx/mac-crafter/Sources/Utils/Shell.swift

index a240ccffa51c2e77ddd836a9c4f7fc435fb3dfd6..1d7a35522c4118b5e9a219e56aea2e488608aa4c 100644 (file)
@@ -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(