golang 打堆栈

func handleSignals(signals chan os.Signal) {
        go func() {
                for {
                        select {
                        case s := <-signals:
                                fmt.Printf("received signal %v ", s)
                                switch s {
                                case syscall.SIGUSR1:
                                        DumpStacks(true)
                                default:
                                }
                        }
                }
        }()
}

func DumpStacks(writeToFile bool) {
        var (
                buf       []byte
                stackSize int
        )
        bufferLen := 16384
        for stackSize == len(buf) {
                buf = make([]byte, bufferLen)
                stackSize = runtime.Stack(buf, true)
                bufferLen *= 2
        }
        buf = buf[:stackSize]
        if writeToFile { // Also write to file to aid gathering diagnostics
                name := filepath.Join(os.TempDir(), fmt.Sprintf("runc.stacks.log", os.Getpid()))
                f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0640)
                if err != nil {
                        return
                }
                defer f.Close()
                f.WriteString(string(buf))
        }
}

main 函数
        sc := make(chan os.Signal, 1)
        handleSignals(sc)
        signal.Notify(sc, syscall.SIGUSR1)

 

posted @ 2025-04-22 19:07  rincloud  阅读(16)  评论(0)    收藏  举报