How to Gracefully Fail at Service Start

ID: Q115829

3.50 3.51 4.00 WINDOWS NT kbprg

The information in this article applies to:

SUMMARY

If an error occurs while your service is running or initializing (SERVICE_START_PENDING) and you need to stop the service process, do the following:

1. Clean up any resources that are being used (threads, memory, and so

   forth). You should start sending a SERVICE_STOP_PENDING status if the
   clean up process is lengthy. Be sure to update the Service Control
   Manager as demonstrated in the Win32 SDK SERVICE sample.

2. Send out a SERVICE_STOPPED status from the last thread to terminate
   before it calls ExitThread().

3. Set SERVICE_STATUS.dwWin32ExitCode and/or
   SERVICE_STATUS.dwServiceSpecificExitCode to values that indicate why the
   service is stopping. If you return a value for the
   dwServiceSpecificErrorCode field, then the dwWin32ExitCode field should
   be set to ERROR_SERVICE_SPECIFIC_ERROR.

   The reason for setting these values is that if a service fails its
   operation, but returns an exit code of 0, the following error message is
   returned by default:

      Error 2140: An internal Windows NT error occurred

MORE INFORMATION

When the last service in the process has terminated (you may have multiple services in the service process), the StartServiceCtrlDispatcher() call in the main thread returns. The main routine should call ExitProcess() because all of the services have terminated.

REFERENCES

There is a termination sample in the "Win32 Programmer's Reference," in the "Services" overview section, "Writing a ServiceMain Function." This is a simple situation where the service process only consists of one thread. This thread returns when it is ready to terminate, instead of calling ExitThread().

Additional reference words: 3.50 3.51 4.00 KBCategory: kbprg KBSubcategory: BseService

Keywords          : kbKernBase kbService kbGrpKernBase 
Version           : 3.50 3.51 4.00
Platform          : NT WINDOWS

Last Reviewed: December 18, 1996