diff --git a/Sources/Console/Console/Console.swift b/Sources/Console/Console/Console.swift index f3062c9b..5261a500 100644 --- a/Sources/Console/Console/Console.swift +++ b/Sources/Console/Console/Console.swift @@ -70,6 +70,10 @@ public protocol ConsoleProtocol { - returns: The return string from the method */ func backgroundExecute(program: String, arguments: [String]) throws -> String + + /// Upon a console instance being killed for example w/ ctrl+c + /// a console should forward the message to kill listeners + func registerKillListener(_ listener: @escaping (Int32) -> Void) } extension ConsoleProtocol { diff --git a/Sources/Console/Terminal/Terminal.swift b/Sources/Console/Terminal/Terminal.swift index 56453d53..517ceb1a 100644 --- a/Sources/Console/Terminal/Terminal.swift +++ b/Sources/Console/Terminal/Terminal.swift @@ -2,6 +2,7 @@ import libc import Foundation private var _pids: [UnsafeMutablePointer] = [] +private var _killListeners: [(Int32) -> Void] = [] public class Terminal: ConsoleProtocol { public enum Error: Swift.Error { @@ -10,7 +11,7 @@ public class Terminal: ConsoleProtocol { } public let arguments: [String] - + /** Creates an instance of Terminal. */ @@ -18,6 +19,10 @@ public class Terminal: ConsoleProtocol { self.arguments = arguments func kill(sig: Int32) { + _killListeners.forEach { listener in + listener(sig) + } + for pid in _pids { _ = libc.kill(pid.pointee, sig) } @@ -156,4 +161,8 @@ public class Terminal: ConsoleProtocol { private func command(_ command: Command) { output(command.ansi, newLine: false) } + + public func registerKillListener(_ listener: @escaping (Int32) -> Void) { + _killListeners.append(listener) + } } diff --git a/Tests/ConsoleTests/Utilities.swift b/Tests/ConsoleTests/Utilities.swift index b6de2f6b..a80d60c1 100644 --- a/Tests/ConsoleTests/Utilities.swift +++ b/Tests/ConsoleTests/Utilities.swift @@ -5,6 +5,10 @@ class TestConsole: ConsoleProtocol { var inputBuffer: String = "" var outputBuffer: String = "" + var size: (width: Int, height: Int) { + return (0, 0) + } + func output(_ string: String, style: ConsoleStyle, newLine: Bool) { outputBuffer += string if newLine { @@ -26,7 +30,7 @@ class TestConsole: ConsoleProtocol { } - var size: (width: Int, height: Int) { - return (0, 0) + func registerKillListener(_ listener: @escaping (Int32) -> Void) { + } }