捕获异常消息,并报告消息类型
package main
import (
"fmt"
"runtime"
"time"
"github.com/silentred/gid"
//"log"
"os"
"os/signal"
"syscall"
)
func RegisterSignalHandler() chan os.Signal {
c := make(chan os.Signal, 1)
//signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)
signal.Notify(c, os.Interrupt, os.Kill)
// s := <-c
// fmt.Println("Got signal:", s)
return c
}
func SignalHandler(c chan os.Signal) {
// Block until a signal is received.
for {
s := <-c
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP:
fmt.Printf("SIGQUIT [#%d] ", gid.Get())
case syscall.SIGINT:
fmt.Println("enter syscall.SIGINT")
case syscall.SIGHUP:
fmt.Printf("SIGHUP [#%d] ", gid.Get())
default:
fmt.Printf("default [#%d] ", gid.Get())
}
}
}
func main() {
sc := RegisterSignalHandler()
go SignalHandler(sc)
runtime.GOMAXPROCS(2)
var i int
fmt.Printf("main goroutine [#%d] ", gid.Get())
for {
time.Sleep(1 * time.Second)
fmt.Println(i)
i++
}
}
捕获Ctrl+C并强制退出程序
func main() {
c := make(chan os.Signal, 1)
//signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)
signal.Notify(c, os.Interrupt, os.Kill)
s := <-c
fmt.Println("Got signal:", s)
}