signal.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Package signal provides helper functions for dealing with signals across
  2. // various operating systems.
  3. package signal
  4. import (
  5. "fmt"
  6. "os"
  7. "os/signal"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. )
  12. // CatchAll catches all signals and relays them to the specified channel.
  13. func CatchAll(sigc chan os.Signal) {
  14. handledSigs := []os.Signal{}
  15. for _, s := range SignalMap {
  16. handledSigs = append(handledSigs, s)
  17. }
  18. signal.Notify(sigc, handledSigs...)
  19. }
  20. // StopCatch stops catching the signals and closes the specified channel.
  21. func StopCatch(sigc chan os.Signal) {
  22. signal.Stop(sigc)
  23. close(sigc)
  24. }
  25. // ParseSignal translates a string to a valid syscall signal.
  26. // It returns an error if the signal map doesn't include the given signal.
  27. func ParseSignal(rawSignal string) (syscall.Signal, error) {
  28. s, err := strconv.Atoi(rawSignal)
  29. if err == nil {
  30. if s == 0 {
  31. return -1, fmt.Errorf("Invalid signal: %s", rawSignal)
  32. }
  33. return syscall.Signal(s), nil
  34. }
  35. signal, ok := SignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]
  36. if !ok {
  37. return -1, fmt.Errorf("Invalid signal: %s", rawSignal)
  38. }
  39. return signal, nil
  40. }
  41. // ValidSignalForPlatform returns true if a signal is valid on the platform
  42. func ValidSignalForPlatform(sig syscall.Signal) bool {
  43. for _, v := range SignalMap {
  44. if v == sig {
  45. return true
  46. }
  47. }
  48. return false
  49. }