我的应用程序使用日志记录管道,因此需要优雅地处理运行时混乱,就像在日志记录管道上传递消息以声明应用程序关闭一样,以便规则引擎可以对其进行处理。
说完了这个目标,我跟着去了doc for signal(https://golang.org/src/os/signal/doc.go),它提到了SIGBUS,SIGFPE和SIGSEGV,但没有明确提到如何在代码中捕获它们。所以我尝试在应用程序中使用测试和信号处理程序,但它不会被调用。有没有办法实现这个目标。
func sigHandler1(exitChannel, syncChannel chan bool) {
c := make(chan os.Signal, 1)
signal.Notify(c)
go func() {
for {
// Block until a signal is received.
s := <-c
mlog.Info(" got signal1: %+v", s)
switch s {
// kill -SIGHUP XXXX
case syscall.SIGHUP, syscall.SIGQUIT,syscall.SIGINT, syscall.SIGTERM:
exitChannel <- true
case syscall.SIGSEGV:
syncChannel <-true
default:
log.Println("Unknown signal.")
}
}
}()
}
func Test() {
var msgBuf []byte
log.Println("Test going to generate panic")
msgBuf[0] = 1
}
恐慌结果如下。
panic: runtime error: index out of range [recovered]
panic: runtime error: index out of range
goroutine 10 [running]:
panic(0x515de0, 0xc420010150)
/usr/local/Cellar/go/1.7.5/libexec/src/runtime/panic.go:500 +0x1a1
testing.tRunner.func1(0xc420092300)
/usr/local/Cellar/go/1.7.5/libexec/src/testing/testing.go:579 +0x25d
panic(0x515de0, 0xc420010150)
/usr/local/Cellar/go/1.7.5/libexec/src/runtime/panic.go:458 +0x243
app.Test()
app/main.go:142 +0x56
app.TestMHProcessDlAck_22(0xc420092300)
app.mh_test.go:946 +0x68
testing.tRunner(0xc420092300, 0x60bc90)
/usr/local/Cellar/go/1.7.5/libexec/src/testing/testing.go:610 +0x81
created by testing.(*T).Run
/usr/local/Cellar/go/1.7.5/libexec/src/testing/testing.go:646 +0x2ec
exit status 2
FAIL app 0.085s