Home >Backend Development >Golang >How to Dump Goroutine Stacks in a Go Process Without Terminating It?
How to Dump Goroutine Stacks Without Terminating a Go Process
A Go process requires the ability to dump stack traces for each goroutine without altering its source code or terminating it. To achieve this, consider implementing a signal handler using the code snippet below:
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) ... }
When a SIGQUIT signal is received, it is forwarded to the designated channel. Subsequently, the runtime.Stack function formats the stack trace into a specified buffer. If the stack trace exceeds the buffer size, it is truncated and printed. As a result, this approach enables the capture of a stack trace for each goroutine without interrupting the running Go process.
The above is the detailed content of How to Dump Goroutine Stacks in a Go Process Without Terminating It?. For more information, please follow other related articles on the PHP Chinese website!