HOWTO: How to Gracefully Fail at Service Start

ID: Q115829


The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API), used with:
    • Microsoft Windows NT versions 3.5, 3.51, 4.0
    • Microsoft Windows 2000


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 query words: 3.50

Keywords : kbFileIO kbKernBase kbWinOS2000 kbService kbDSupport kbGrpKernBase
Version : winnt:3.5,3.51,4.0
Platform : winnt
Issue type : kbhowto


Last Reviewed: January 5, 2000
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.