How can I see if the GoLand debugger is running in the program?

Issue

In C# the executing program can detect if it’s running in the debugger using:

System.Diagnostics.Debugger.IsAttached

Is there an equivalent in Go? I have some timeouts which I would like to be disabled while I am stepping through the code. Thanks!

I am using the GoLand debugger.

Solution

If you assume that the debugger used will be Delve, you can check on the Delve process(es). There are at least two cases to consider (maybe more).

  1. Delve launched your process. In this case, when you call os.Getppid() to get the pid of your parent process, that process will be Delve.
  2. Delve didn’t launch your process, but did attach to it later. In this case, you’d need to look for all running Delve processes, look at their command lines, and see if any was launched with a command line including “attach “, where is the result of calling os.Getpid(). This relies on the assumption that you’re not finding an old Delve, running with an older PID that happens to match yours. (I forget what the rules on on reuse of PIDs by the OS).

Note that the os functions used by 1 and 2 are different. One gets the parent PID, the other gets your PID.

Some very basic code to do 1 looks like this:

func isLaunchedByDebugger() bool {
    // gops executable must be in the path. See https://github.com/google/gops
    gopsOut, err := exec.Command("gops", strconv.Itoa(os.Getppid())).Output()
    if err == nil && strings.Contains(string(gopsOut), "\\dlv.exe") {
        // our parent process is (probably) the Delve debugger
        return true
    }
    return false
}

Answered By – John Rusk – MSFT

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.