问题
I'm trying to attach the ClrMD in a process to itself:
private static void Main()
{
var pid = Process.GetCurrentProcess().Id;
WriteLine($"PID: {pid}");
using (var dataTarget = DataTarget.AttachToProcess(pid, 1000))
{
WriteLine($"ClrMD attached");
}
}
However, I'm getting the following exception:
PID: 7416
Unhandled Exception: Microsoft.Diagnostics.Runtime.ClrDiagnosticsException: Could not attach to pid 1CF8, HRESULT: 0x80070057
at Microsoft.Diagnostics.Runtime.DbgEngDataReader..ctor(Int32 pid, AttachFlag flags, UInt32 msecTimeout)
at Microsoft.Diagnostics.Runtime.DataTarget.AttachToProcess(Int32 pid, UInt32 msecTimeout, AttachFlag attachFlag)
at Microsoft.Diagnostics.Runtime.DataTarget.AttachToProcess(Int32 pid, UInt32 msecTimeout)
at BanksySan.Scratch.Console.Program.Main(String[] args)
I can attach in passive mode, but not in Invasive or Non-Invasive mode.
回答1:
You can use DataTarget.CreateSnapshotAndAttach
.
This method creates a snapshot of the process and create DataTarget
from it.
Example:
var processId = Process.GetCurrentProcess().Id;
using (var dataTarget = DataTarget.CreateSnapshotAndAttach(processId))
{
}
回答2:
Invasive
flag allows the consumer of this API to control the target process through normal IDebug function calls. The process will be paused by this (for the duration of the attach) in order to get the data and control the target process
In a NonInvasive
debugger attach, the process will be paused by this (for the duration of the attach) and would be able to get the data but the caller cannot control the target process. This is useful when there's already a debugger attached to the process.
Performing a Passive
attach means that no debugger is actually attached to the target process. The process is not paused, so queries for quickly changing data (such as the contents of the GC heap or callstacks) will be highly inconsistent unless the user pauses the process through other means. It is useful when attaching with ICorDebug (managed debugger), as you cannot use a non-invasive attach with ICorDebug.
来源:https://stackoverflow.com/questions/47621896/attach-to-self-with-clrmd-hresult-0x80070057