使用golang函数signal.Notify,程序可以响应SIGINT、SIGKILL等过程信号。 特别是指注册事件处理程序。 但是,谷歌用户应该避免捕获SIGABRT,在本博客中说明了理由。
下面的程序解释了为什么捕获SIGABRT是个坏主意:
packagemainimport (' fmt ' ' OS ' ' OS/signal ' ' strings ' ' syscall ' ) (func main ) )/printtheprocessidtomakeiteasiertosendthisprogramasignal.fmt.printf (PID : % dn ), os.Getpid ()//ifthisprogram ' sfirstargumentis ' trap ' thentrapsigabrt.if len (OS.args )1strings.equalfold ) OOS 1 ) signal.Notify(n ) n, syscall.sigaBRT(gofunc ) ) forSIG:=rangen ) fmt.println (SIG ) os.Exit(1) () ) )/useachanenent
$ go run main.gopID: 14755程序打印进程id并等待信号,或者使用kill命令,如果程序在前台运行,则使用Ctrl-C。
$ gorunmain.gopid :14755 ^ csignal : interrupt以信号方式终止进程并不是什么新鲜事。 但是,
谷歌程序将SIGABRT解释为特殊事件,如果发生死锁,core dump将包含所有协议。 golangprogramsinterpretthesigabrtsignalasaspecialeventthatforcesacoredump,includingallgoroutinesandifthey’re deadlocked .是
$ go run main.gopid: 14765在另一个会话中发送SIGABRT:
$ kill -SIGABRT 14765原文:
3359 akutz.WordPress.com/2017/10/02/golang-and-siga BRT /