This is a creation in Article, where the information may have evolved or changed.
Capturing and processing signals can be achieved with elegant start and restart. The signal of Golang provides the relevant methods. Here is a template, directory structure:
├──sig│└──sig.go└──test.go
First look at how to invoke:
1.new out an Object
2.register signal and corresponding processing function
3. Define the OS. Signal type of channel, called Signal. Notify
4.for+select Loop, the original logic is placed in the default branch.
Package main import (. "./sig" "FMT" "OS" "Os/signal" "Syscall" "Time") var stopflag_ bool Func main () {sighandler: = signal Setnew () Sighandler.register (syscall. Sigquit, Sighandlerfunc) sighandler.register (syscall. SIGUSR1, Sighandlerfunc) sighandler.register (syscall. SIGUSR2, Sighandlerfunc) Sigchan: = Make (chan os. Signal, Signal. Notify (Sigchan) for true {select {case sig: = <-sigchan:err: = Sighandler.handle (SIG, N IL) if err! = Nil {fmt. Printf ("[ERROR] Unknown signal received:%v\n", SIG) Os. Exit (1)} default:time. Sleep (time. Duration (3) * time. Second)}}} func Sighandlerfunc (S OS). Signal, Arg interface{}) {switch s {case Syscall. SIGUSR1://Check FMT. Printf ("Stopping Status:%v\n", stopflag_) case Syscall. SIGUSR2://Run Formerflag: = Stopflag_ Stopflag_ = False fmt. Printf ("Stopping status changed from%v to%v\n ", Formerflag, Stopflag_) case Syscall. Sigquit://stop Formerflag: = Stopflag_ Stopflag_ = True FMT. Printf ("Stopping Status changed from%v to%v\n", Formerflag, Stopflag_)}}
Definition of SIG Package (Sig/sig.go):
Package sig Import ( "FMT" "OS") 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 (Sig OS. Signal, Arg interface{}) (err error) { If _, found: = Set.m[sig]; found { Set.m[sig] (SIG, Arg) return Nil
} else { return FMT. Errorf ("No handler available for signal%v", SIG) } Panic ("won ' t reach here")}