Process.swift 992 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. //
  2. // Process
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public class Process {
  9. public static var pid: Int {
  10. return Int(getpid())
  11. }
  12. public static var tid: UInt64 {
  13. #if os(Linux)
  14. return UInt64(pthread_self())
  15. #else
  16. var tid: __uint64_t = 0
  17. pthread_threadid_np(nil, &tid)
  18. return UInt64(tid)
  19. #endif
  20. }
  21. private static var signalsWatchers = [(Int32) -> Void]()
  22. private static var signalsObserved = false
  23. public static func watchSignals(_ callback: @escaping (Int32) -> Void) {
  24. if !signalsObserved {
  25. [SIGTERM, SIGHUP, SIGSTOP, SIGINT].forEach { item in
  26. signal(item) { signum in
  27. Process.signalsWatchers.forEach { $0(signum) }
  28. }
  29. }
  30. signalsObserved = true
  31. }
  32. signalsWatchers.append(callback)
  33. }
  34. }