Dumping Goroutine Stacks Without Halting Process in Go
Given a running Go process, capturing stack traces for all its goroutines can be achieved without code modifications or process termination. Here's a solution to fulfill the requirements:
Implementation:
Signal Handler:
Signal Notification:
Stack Trace Dumping:
Example Code:
<code class="go">import ( "fmt" "os" "os/signal" "runtime" "syscall" ) func main() { // Create a channel to receive signals sigChan := make(chan os.Signal) // Start a goroutine to listen for signals and dump stack traces go func() { stacktrace := make([]byte, 8192) for _ = range sigChan { length := runtime.Stack(stacktrace, true) fmt.Println(string(stacktrace[:length])) } }() // Notify the process to listen for SIGQUIT signals and send them to sigChan signal.Notify(sigChan, syscall.SIGQUIT) // Do some other work here... }</code>
By running this code, you can trigger stack trace dumping by sending SIGQUIT to the Go process without killing it. To do so, use kill -6
The above is the detailed content of How to Dump Goroutine Stacks Without Stopping a Go Process?. For more information, please follow other related articles on the PHP Chinese website!