Skip to content

Instantly share code, notes, and snippets.

@zored
Created May 13, 2022 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zored/aafb6eaf6d02813b377306d508b1b333 to your computer and use it in GitHub Desktop.
Save zored/aafb6eaf6d02813b377306d508b1b333 to your computer and use it in GitHub Desktop.
Kill frozen dlv --headless on macOS
package main
import (
"fmt"
"github.com/mitchellh/go-ps"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
defer deferredKillDlv()()
fmt.Println("exit me or wait for 5 secs...")
time.Sleep(5 * time.Second)
}
func deferredKillDlv() func() {
pid := getDlvPid()
if pid == 0 {
return func() {}
}
kill := func() {
p := recover()
if p != nil {
fmt.Printf("panic recovered: %v\n", p)
}
_ = syscall.Kill(pid, syscall.SIGINT)
}
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-s
kill()
}()
return kill
}
func getDlvPid() int {
dlvPid := 0
for pid := os.Getpid(); pid > 0; {
p, _ := ps.FindProcess(pid)
if p.Executable() == "dlv" {
dlvPid = pid
break
}
if pid == p.PPid() {
break
}
pid = p.PPid()
}
return dlvPid
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment