How can I dump all a Go process's stacks without killing it?

前端 未结 2 669
日久生厌
日久生厌 2020-12-30 05:19

A Go process is running. I want to

  1. dump a stack trace for each of its goroutines
  2. from the outside, without depending on anything I add to its source c
2条回答
  •  既然无缘
    2020-12-30 05:44

    You can set up a handler like that using code something like this:

    import (
        "fmt"
        "os"
        "os/signal"
        "runtime"
        "syscall"
    )
    
    func main() {
        sigChan := make(chan os.Signal)
        go func() {
            stacktrace := make([]byte, 8192)
            for _ = range sigChan {
                length := runtime.Stack(stacktrace, true)
                fmt.Println(string(stacktrace[:length]))
            }
        }()
        signal.Notify(sigChan, syscall.SIGQUIT)
    
    
        ...
    }
    

    The SIGQUIT signal will now be caught and sent to the given channel. The runtime.Stack function is then used to format the stack trace into a prepared buffer (if it is larger than the buffer, it will be truncated), and then printed.

提交回复
热议问题