What is the best way to attach a debugger to a process in VC++ at just the right point in time?

another variant, which I sometimes use is

while( !::IsDebuggerPresent() )
    ::Sleep( 100 ); // to avoid 100% CPU load

it should just silently wait until you attach your debugger to the process.


you can use DebugBreak, check these links:

http://www.epsilon-delta.net/articles/vc6_debug.html#breaking-with-debugbreak

http://blogs.msdn.com/calvin_hsia/archive/2006/08/25/724572.aspx


To attach a debugger at a particular point, you have several options:

The simplest is just to call DebugBreak, which is pretty much equivalent to __asm int 3, but also works on other architectures (MSVC for x64 doesn't allow inline assembly, if I recall correctly). This'll bring up the just-in-time debugger window, and you'll be able to select from registered debuggers (i.e. Visual Studio) to attach to the process.

Alternatively, you can introduce a call to Sleep, giving you an opportunity to attach the debugger. You should use #ifdef _DEBUG around this, to ensure that you don't actually ship with this code included.

One question: why can't you run the code from the IDE? Is it a service or an IIS-loaded DLL or similar?

In this case, you can check out the ImageFileExecutionOptions registry key, which allows you to attach a debugger at the moment that the process starts.

If you use cdb for this, you can configure it as either server or client to a WinDbg instance, and debug that way. I've done this in the past by using WinDbg as a kernel debugger, and by using ImageFileExecutionOptions to start ntsd -d with the named process. This causes WinDbg to break into user mode. This is sometimes a useful technique.