Process.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. * Copyright 2025 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Dispatch
  17. import Foundation
  18. public extension Process {
  19. /// Creates a new `Process` instance without running it.
  20. ///
  21. /// - Parameters:
  22. /// - exe: The executable to run.
  23. /// - args: An array of arguments to pass to the executable.
  24. /// - env: A map of environment variables to set for the process.
  25. /// - inheritEnvironment: When enabled, the parent process' environvment will also be applied
  26. /// to this process. Effectively, this means that any environvment variables declared within the
  27. /// parent process will propogate down to this new process.
  28. convenience init(_ exe: String,
  29. _ args: [String] = [],
  30. env: [String: String] = [:],
  31. inheritEnvironment: Bool = false) {
  32. self.init()
  33. executableURL = URL(filePath: "/usr/bin/env")
  34. arguments = [exe] + args
  35. environment = env
  36. if inheritEnvironment {
  37. mergeEnvironment(ProcessInfo.processInfo.environment)
  38. }
  39. }
  40. /// Merges the provided environment variables with this process' existing environment variables.
  41. ///
  42. /// If an environment variable is already set, then it will **NOT** be overwritten. Only
  43. /// environment variables not currently set on the process will be applied.
  44. ///
  45. /// - Parameters:
  46. /// - env: The environment variables to merge with this process.
  47. func mergeEnvironment(_ env: [String: String]) {
  48. guard environment != nil else {
  49. // if this process doesn't have an environment, we can just set it instead of merging
  50. environment = env
  51. return
  52. }
  53. environment = environment?.merging(env) { current, _ in current }
  54. }
  55. /// Run the process with signals from the parent process.
  56. ///
  57. /// The signals `SIGINT` and `SIGTERM` will both be propogated
  58. /// down to the process from the parent process.
  59. ///
  60. /// This function will not return until the process is done running.
  61. ///
  62. /// - Parameters:
  63. /// - args: Optionally provide an array of arguments to run the process with.
  64. ///
  65. /// - Returns: The exit code that the process completed with.
  66. @discardableResult
  67. func runWithSignals(_ args: [String]? = nil) throws -> Int32 {
  68. if let args {
  69. arguments = (arguments ?? []) + args
  70. }
  71. let sigint = bindSignal(signal: SIGINT) {
  72. if self.isRunning {
  73. self.interrupt()
  74. }
  75. }
  76. let sigterm = bindSignal(signal: SIGTERM) {
  77. if self.isRunning {
  78. self.terminate()
  79. }
  80. }
  81. sigint.resume()
  82. sigterm.resume()
  83. try run()
  84. waitUntilExit()
  85. return terminationStatus
  86. }
  87. }
  88. /// Binds a callback to a signal from the parent process.
  89. ///
  90. /// ```swift
  91. /// bindSignal(SIGINT) {
  92. /// print("SIGINT was triggered")
  93. /// }
  94. /// ```
  95. ///
  96. /// - Parameters:
  97. /// - signal: The signal to listen for.
  98. /// - callback: The function to invoke when the signal is received.
  99. func bindSignal(signal value: Int32,
  100. callback: @escaping DispatchSourceProtocol
  101. .DispatchSourceHandler) -> any DispatchSourceSignal {
  102. // allow the process to survive long enough to trigger the callback
  103. signal(value, SIG_IGN)
  104. let dispatch = DispatchSource.makeSignalSource(signal: value, queue: .main)
  105. dispatch.setEventHandler(handler: callback)
  106. return dispatch
  107. }