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)