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:
#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[])
{
RuntimeDiagnostics::CheckPauseOnStartupOption();
return 0;
}
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]"PauseOnStartup"=dword:00000001