【问题标题】:Is there a way to detect if a debugger is attached to another process from C#?有没有办法检测调试器是否从 C# 附加到另一个进程?
【发布时间】:2011-01-12 09:23:53
【问题描述】:

我有一个程序 Process.Start() 另一个程序,它在 N 秒后将其关闭。

有时我选择将调试器附加到已启动的程序中。在这些情况下,我不希望进程在 N 秒后关闭。

我希望主机程序检测是否连接了调试器,因此它可以选择不关闭它。

澄清:我不希望检测是否有调试器附加到 my 进程,我希望检测是否有调试器附加到我的进程产生了。

【问题讨论】:

    标签: c# debugging


    【解决方案1】:
    if(System.Diagnostics.Debugger.IsAttached)
    {
        // ...
    }
    

    【讨论】:

    • 这不是告诉我调试器是否附加到主机进程吗?我正在寻找一种方法来确定是否正在调试生成的进程。
    • 我明白了,很抱歉误解了您的问题。我相信生成的进程是唯一可以查询该信息的进程。如果您设置某种形式的进程间通信,那将允许原始进程轮询调试器状态。
    【解决方案2】:

    您需要将P/Invoke 降至CheckRemoteDebuggerPresent。这需要目标进程的句柄,您可以从 Process.Handle 中获取该句柄。

    【讨论】:

      【解决方案3】:

      当前进程是否正在调试?

      var isDebuggerAttached = System.Diagnostics.Debugger.IsAttached;
      

      是否正在调试另一个进程?

      Process process = ...;
      bool isDebuggerAttached;
      if (!CheckRemoteDebuggerPresent(process.Handle, out isDebuggerAttached)
      {
          // handle failure (throw / return / ...)
      }
      else
      {
          // use isDebuggerAttached
      }
      
      
      /// <summary>Checks whether a process is being debugged.</summary>
      /// <remarks>
      /// The "remote" in CheckRemoteDebuggerPresent does not imply that the debugger
      /// necessarily resides on a different computer; instead, it indicates that the 
      /// debugger resides in a separate and parallel process.
      /// <para/>
      /// Use the IsDebuggerPresent function to detect whether the calling process 
      /// is running under the debugger.
      /// </remarks>
      [DllImport("Kernel32.dll", SetLastError=true, ExactSpelling=true)]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool CheckRemoteDebuggerPresent(
          SafeHandle hProcess,
          [MarshalAs(UnmanagedType.Bool)] ref bool isDebuggerPresent);
      

      在 Visual Studio 扩展中

      Process process = ...;
      bool isDebuggerAttached = Dte.Debugger.DebuggedProcesses.Any(
          debuggee => debuggee.ProcessID == process.Id);
      

      【讨论】:

        【解决方案4】:

        我知道这是旧的,但我遇到了同样的问题并意识到如果你有指向 EnvDTE 的指针,你可以检查进程是否在 Dte.Debugger.DebuggedProcesses

        foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) {
          if (p.ProcessID == spawnedProcess.Id) {
            // stuff
          }
        }
        

        CheckRemoteDebuggerPresent 调用仅检查进程是否正在本地调试,我相信 - 它不适用于检测托管调试。

        【讨论】:

          【解决方案5】:

          我的解决方案是 Debugger.IsAttached,如下所述:http://www.fmsinc.com/free/NewTips/NET/NETtip32.asp

          【讨论】:

            猜你喜欢
            • 2014-09-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-05
            • 2012-09-15
            相关资源
            最近更新 更多