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

后端 未结 3 1283
-上瘾入骨i
-上瘾入骨i 2021-01-14 15:52

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

System.Diagnostics.Debugger.IsAttached

Is there an equivalen

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 15:57

    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
    }
    

提交回复
热议问题