How can I flush all stacks of a Go process without killing it?

The Go process is running. I want

  1. unload stack trace for each of its programs
  2. from the outside, regardless of what I add to its source code
  3. without killing him.

How can i do this?

It should be easy - a function was requested: https://code.google.com/p/go/issues/detail?id=2516 and, according to the conclusion of this thread, it is implemented. That was over two years ago. But neither the problem branch nor the commit contain hints on how to call this function.

A function request referred to SIGQUIT as a signal that the JVM receives to invoke the corresponding function. But SIGQUIT is not the answer; at least on go1.2 SIGQUIT executes # 1 and # 2, but also kills the process.

Someone asked a related question here a while ago: How to dump dumps from the goroutine stack? but they clearly did not ask for No. 2 or No. 3, none of the answers matches No. 2, and they accepted an answer that does not correspond to No. 2. So this is another question.

+10
go
source share
2 answers

If you use net / http, you can access goroutines through debug handlers. If you look at the following source

http://golang.org/src/pkg/runtime/pprof/pprof.go

You will see the goroutineProfile profile on line 62. This profile is written through writeGoroutine . If writeGoroutine is called using debug> = 2, it writes out all the goroutines.

You should be able to curl http://localhost:<port>/debug/pprof/goroutine?debug=2 to get all the goroutines reset. Unfortunately, I did not see links to signal handlers that call this code, but you can see links to how pprof uses runtime.Stack in the source code to implement this yourself quite easily.

+3
source share

You can set up such a handler using code 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 this channel. The runtime.Stack function runtime.Stack 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.

+10
source share

All Articles