Created
October 16, 2017 09:08
-
-
Save limboinf/bd527d1f4ee78ebce2b671b07b072b09 to your computer and use it in GitHub Desktop.
[go signal] #go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"os" | |
"os/signal" | |
"syscall" | |
) | |
type signalHandler func(s os.Signal, arg interface{}) | |
type signalSet struct { | |
m map[os.Signal]signalHandler | |
} | |
func signalSetNew() (*signalSet) { | |
ss := new(signalSet) | |
ss.m = make(map[os.Signal]signalHandler) | |
return ss | |
} | |
func (set *signalSet) register(s os.Signal, handler signalHandler) { | |
if _, found :=set.m[s]; !found { | |
set.m[s] = handler | |
} | |
} | |
func (set *signalSet) handle(s os.Signal, arg interface{}) (err error) { | |
if _, found := set.m[s]; found { | |
set.m[s](s, arg) | |
return nil | |
} else { | |
return fmt.Errorf("unregister signal: %v", s) | |
} | |
} | |
func main() { | |
go sysSignalHandleDemo() | |
time.Sleep(time.Hour) // make the main goroutine wait! | |
} | |
func sysSignalHandleDemo() { | |
ss := signalSetNew() | |
handler := func(s os.Signal, arg interface{}) { | |
fmt.Printf("handle signal: %v\n", s) | |
} | |
ss.register(syscall.SIGINT, handler) | |
ss.register(syscall.SIGUSR1, handler) | |
ss.register(syscall.SIGUSR2, handler) | |
for { | |
c := make(chan os.Signal) | |
var sigs []os.Signal | |
for sig := range ss.m { | |
sigs = append(sigs, sig) | |
} | |
signal.Notify(c) | |
sig := <-c | |
err := ss.handle(sig, nil) | |
if (err != nil) { | |
fmt.Printf("unknown signal received: %v\n", sig) | |
os.Exit(1) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment