Sometimes you need to debug a process, and you need to attach the debugger right away, but you cannot launch the process under the debugger. For example, if the process you need to debug is a Windows Service, the Windows Service Manager must launch the process. How can you debug it?
Here are the two easiest solutions:
#1: Windows includes registry settings under the ‘Image File Execution Options’ key that can help you debug this. I blogged about this before back in February of 2005 (http://blogs.msdn.com/greggm/archive/2005/02/21/377663.aspx). Most of the information is that blog is still correct. A few updates worth mentioning though:
- Visual Studio 2008 can support session 0 processes on Vista or Server 2008.
- Visual Studio 2008 can support 64-bit operating systems. The only remaining 64-bit restriction is that 64-bit managed processes cannot be debugged this way since the .NET Framework does not support managed+native debugging of 64-bit processes.
- Visual Studio 2005 does not support this feature on Windows Vista or Server 2008. You will need to upgrade to 2008 for these operating systems.
#2: You can add code to your app to cause it to pause waiting for a debugger to attach. I am attaching an example header file for making this work. We ship several executables that embed similar code for this reason. Just call ‘RuntimeDiagnostics::CheckPauseOnStartupOption()’ as the first line of code in your main routine. You can do something verify similar for managed code as well. Just call ‘System.Diagnostics.Debugger.IsAttached’ instead of IsDebuggerPresent.
int _tmain(int argc, _TCHAR* argv)
Then set this registy key if you need your app to pause:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sample.exe]