编辑
2024-09-25
Cheat Sheets
0

目录

测试
参考

在编写 Go 代码时很容易忘记判断 nil 从而发生 panic,当 panic 没有使用recover()捕获时,程序将没有任何征兆就退出了,这对追溯原因造成很大困难,而 core dump 可以解决这个问题。

测试

  1. 启用 core dump
shell
ulimit -c unlimited
  1. 准备一个会 panic 的 Go 程序
go
package main import ( "fmt" "math/rand" "runtime/debug" "time" ) func main() { // 打印各种堆栈信息 debug.SetTraceback("crash") go func() { arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for { index := rand.Intn(11) fmt.Println(arr[index]) } }() time.Sleep(time.Second * 5) }
  1. 编译与运行
shell
go build main.go ./main 3 2 3 3 6 10 6 5 1 2 9 3 9 10 panic: runtime error: index out of range [10] with length 10 ...(省略各种栈信息)
  1. 使用 dlv 调试
shell
# dlv 调试 core 的命令格式 dlv core <executable> <core> [flags]
shell
# 生成的 core 文件就在当前目录,文件名也是 core dlv core main core Type 'help' for list of commands. (dlv) bt # 看这儿,打印栈信息 0 0x00000000004674e1 in runtime.raise at /data/software/go/src/runtime/sys_linux_amd64.s:154 1 0x000000000044bb25 in runtime.dieFromSignal at /data/software/go/src/runtime/signal_unix.go:923 2 0x000000000044c146 in runtime.sigfwdgo at /data/software/go/src/runtime/signal_unix.go:1128 3 0x000000000044a745 in runtime.sigtrampgo at /data/software/go/src/runtime/signal_unix.go:432 4 0x00000000004674e1 in runtime.raise at /data/software/go/src/runtime/sys_linux_amd64.s:153 5 0x000000000044bb25 in runtime.dieFromSignal at /data/software/go/src/runtime/signal_unix.go:923 6 0x0000000000435a25 in runtime.crash at /data/software/go/src/runtime/signal_unix.go:1005 7 0x0000000000435a25 in runtime.fatalpanic at /data/software/go/src/runtime/panic.go:1244 8 0x0000000000434998 in runtime.gopanic at /data/software/go/src/runtime/panic.go:779 9 0x0000000000433a1c in runtime.goPanicIndex at /data/software/go/src/runtime/panic.go:114 10 0x0000000000488250 in main.main.func1 at ./main.go:17 # 看这儿 11 0x0000000000465cc1 in runtime.goexit at /data/software/go/src/runtime/asm_amd64.s:1695
shell
(dlv) frame 10 # 看这儿,跳转到指定栈帧 > runtime.raise() /data/software/go/src/runtime/sys_linux_amd64.s:154 (PC: 0x4674e1) Warning: debugging optimized function Frame 10: ./main.go:17 (PC: 488250) 12: 13: go func() { 14: arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 15: for { 16: index := rand.Intn(11) => 17: fmt.Println(arr[index]) # panic 的位置 18: } 19: }() 20: 21: time.Sleep(time.Second * 5) 22: } (dlv) quit # 退出

参考

本文作者:jdxj

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!