我有一个正在运行的upstart作业(某种TCP服务器)。偶尔我的进程重新启动,我可以看到我的系统日志中的下一行:
kernel: [2422352.460162] init: <job_name> main process (16545) killed by TERM signal
我不明白内核发出此TERM信号的原因所以我决定在终止之前捕获信号并打印一些内存和goroutines统计信息。
所以现在我的代码看起来像这样:
func main() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGTERM)
go func() {
s := <-sigc
numOfGoRoutines := runtime. NumGoroutine()
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
log.Println("Got Signal ", s)
log.Println("num of goroutines: ", numOfGoRoutines)
log.Println("Memory Allocated: ", stats.Alloc)
os.Exit(1)
}()
someInfiniteLoopFunction() // this function defined in a different file.
现在奇怪的是,即使手动停止作业,我的goroutine也没有捕捉到TERM信号。
更有意思的是,如果我在信号处理器goroutine之后立即添加Sleep 100秒并在此睡眠期间停止工作,那么我的goroutine会捕获TERM信号。
我在这里绝对无能为力,感谢任何帮助。
答案 0 :(得分:-1)
UPD。抱歉,我现在正确阅读了。也许你的goroutine不等待信号并执行os.Exit()
。尝试添加另一个陈。
func main() {
sigc := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigc, syscall.SIGTERM)
go func() {
s := <-sigc
numOfGoRoutines := runtime. NumGoroutine()
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
log.Println("Got Signal ", s)
log.Println("num of goroutines: ", numOfGoRoutines)
log.Println("Memory Allocated: ", stats.Alloc)
done <- true
os.Exit(1)
}()
<-done
someInfiniteLoopFunction() // this function defined in a different file.