How to Gracefully Fail at Service Start

Last reviewed: December 16, 1996
Article ID: Q115829
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.5, 3.51, and 4.00
    

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


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: December 16, 1996
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.