summaryrefslogtreecommitdiffstats
path: root/signals.go
diff options
context:
space:
mode:
authorSebastien Douheret <sebastien.douheret@iot.bzh>2018-02-23 22:13:22 +0100
committerSebastien Douheret <sebastien.douheret@iot.bzh>2018-02-23 22:13:22 +0100
commit2231e3eae86c5e3ae05e30f667d331f5875c7884 (patch)
tree44c56c9d8b3bb4c6cbee26bedc2c0aec9d9bb5f1 /signals.go
parent84273d6128b7c3c9d31c2f3a1453107a78e949a9 (diff)
Added target and terminal supportv1.1.0
Signed-off-by: Sebastien Douheret <sebastien.douheret@iot.bzh>
Diffstat (limited to 'signals.go')
-rw-r--r--signals.go70
1 files changed, 70 insertions, 0 deletions
diff --git a/signals.go b/signals.go
new file mode 100644
index 0000000..042257e
--- /dev/null
+++ b/signals.go
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "os/signal"
+)
+
+// OnSignalCB callback type for signal
+type OnSignalCB func(sig os.Signal)
+
+// MonSignals .
+type MonSignals struct {
+ callback map[string][]OnSignalCB
+ registeredSignals []os.Signal
+}
+
+var monSig MonSignals
+
+// MonitorSignals Routine used to monitor signals (eg. SIGINT, SIGTERM, ...)
+func MonitorSignals() {
+
+ monSig.callback = make(map[string][]OnSignalCB)
+ monSig.registeredSignals = GetRegisteredSignals()
+
+ sigs := make(chan os.Signal, 1)
+ signal.Notify(sigs, monSig.registeredSignals...)
+
+ go func() {
+ for {
+ sig := <-sigs
+ Log.Debugf("Detect signal %v", sig)
+ if cbArr, exist := monSig.callback[sig.String()]; exist {
+ for _, cb := range cbArr {
+ cb(sig)
+ }
+ }
+ }
+ }()
+}
+
+// isSupportSignal Check if a signal is supported or not
+func isSupportSignal(sig os.Signal) bool {
+ for _, s := range monSig.registeredSignals {
+ if s == sig {
+ return true
+ }
+ }
+ return false
+}
+
+// OnSignal Register a callback for a specified signal
+func OnSignal(sig os.Signal, fCB OnSignalCB) error {
+ if !isSupportSignal(sig) {
+ return fmt.Errorf("unsupported signal %v", sig)
+ }
+ sigStr := sig.String()
+ monSig.callback[sigStr] = append(monSig.callback[sigStr], fCB)
+ return nil
+}
+
+// OnSignals Register a callback for any signals
+func OnSignals(fCB OnSignalCB) error {
+ for _, s := range monSig.registeredSignals {
+ if err := OnSignal(s, fCB); err != nil {
+ return err
+ }
+ }
+ return nil
+}