Service debugging…

Debugging services isn’t all that difficult, but one thing about it which is a pain is attaching a debugger before anything interesting happens. One little trick is to spin in a loop after the service has been created until a debugger is attached.

void _WaitForDebugger( SC_SERVICE_STATUS_HANDLE hServiceStatus, SERVICE_STATUS& ServiceStatus ) {
  while ( !IsDebuggerPresent() ) {
    ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    ServiceStatus.dwCheckPoint = 1;
    ServiceStatus.dwWaitHint = 2000;
    SetServiceStatus(hServiceStatus, &ServiceStatus);

The main thing to note is that the SCM should be notified that the service is still starting on a regular basis. If this isn’t done then the SCM may timeout waiting for the service to start properly.

If you’re using ATL’s CServiceModuleT class then a good place to use this is in an overloaded Run() method on the custom module class.

HRESULT MyServiceModule::Run( int nShowCmd ) throw() {
#ifdef _DEBUG
  _WaitForDebugger(m_hServiceStatus, m_status);
#endif /* _DEBUG */
  return __super::Run(nShowCmd);

This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s