interrupt_unix.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build !windows,!plan9
  15. // InterruptHandler is a function that is called on receiving a
  16. // SIGTERM or SIGINT signal.
  17. package osutil
  18. import (
  19. "log"
  20. "os"
  21. "os/signal"
  22. "sync"
  23. "syscall"
  24. )
  25. type InterruptHandler func()
  26. var (
  27. interruptRegisterMu, interruptExitMu sync.Mutex
  28. // interruptHandlers holds all registered InterruptHandlers in order
  29. // they will be executed.
  30. interruptHandlers = []InterruptHandler{}
  31. )
  32. // RegisterInterruptHandler registers a new InterruptHandler. Handlers registered
  33. // after interrupt handing was initiated will not be executed.
  34. func RegisterInterruptHandler(h InterruptHandler) {
  35. interruptRegisterMu.Lock()
  36. defer interruptRegisterMu.Unlock()
  37. interruptHandlers = append(interruptHandlers, h)
  38. }
  39. // HandleInterrupts calls the handler functions on receiving a SIGINT or SIGTERM.
  40. func HandleInterrupts() {
  41. notifier := make(chan os.Signal, 1)
  42. signal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)
  43. go func() {
  44. sig := <-notifier
  45. interruptRegisterMu.Lock()
  46. ihs := make([]InterruptHandler, len(interruptHandlers))
  47. copy(ihs, interruptHandlers)
  48. interruptRegisterMu.Unlock()
  49. interruptExitMu.Lock()
  50. log.Printf("received %v signal, shutting down...", sig)
  51. for _, h := range ihs {
  52. h()
  53. }
  54. signal.Stop(notifier)
  55. pid := syscall.Getpid()
  56. // exit directly if it is the "init" process, since the kernel will not help to kill pid 1.
  57. if pid == 1 {
  58. os.Exit(0)
  59. }
  60. syscall.Kill(pid, sig.(syscall.Signal))
  61. }()
  62. }
  63. // Exit relays to os.Exit if no interrupt handlers are running, blocks otherwise.
  64. func Exit(code int) {
  65. interruptExitMu.Lock()
  66. os.Exit(code)
  67. }