The ServiceMain function is the entry point for a service.
When a service control program requests that a new service run, the SCM starts the service and sends a start request to the control dispatcher. The control dispatcher creates a new thread to execute the ServiceMain function for the service.
The ServiceMain function should perform the following tasks:
1.Call the RegisterServiceCtrlHandler function immediately to register a Handler function to handle control requests for the service. The return value of RegisterServiceCtrlHandler is a service status handle that will be used in calls to notify the SCM of the service status.
2.Perform initialization. If the execution time of the initialization code is expected to be very short (less than one second), initialization can be performed directly in ServiceMain.
If the initialization time is expected to be longer than one second, call the SetServiceStatus function, specifying the SERVICE_START_PENDING service state in the SERVICE_STATUS structure. As initialization continues, the service should make additional calls to SetServiceStatus to report progress. Sending multiple SetServiceStatus calls is useful for debugging services.
3.When initialization is complete, call SetServiceStatus, specifying the SERVICE_RUNNING state in the SERVICE_STATUS structure.
4.Perform the service tasks, or, if there are no pending tasks, return. Any change in the state of the service warrants a call to SetServiceStatus to report new status information.
5.If an error occurs while the service is initializing or running, the service should call SetServiceStatus, specifying the SERVICE_STOP_PENDING state in the SERVICE_STATUS structure, if cleanup will be lengthy. Once cleanup is complete, call SetServiceStatus from the last thread to terminate, specifying SERVICE_STOPPED in the SERVICE_STATUS structure. Be sure to set the dwServiceSpecificExitCode and dwWin32ExitCode members of the SERVICE_STATUS structure to identify the error.
For more information, see Writing a ServiceMain Function.