Creating a Windows NT/Windows 2000 Service

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Environment:

Introduction

A Windows service is an EXE specially designed to communicate with the Service Control Manager (SCM) of Windows NT/2000. The SCM maintains a database of installed services and driver services, and provides a unified and secure means of controlling them. The SCM is started at system boot and it is a remote procedure call (RPC) server. As a developer trying a simple service, you can divide the program in to four parts.

  1. Main program of Win 32/Console application.
  2. A so-called ServiceMain(), the main program of Service. It’s the entry point of a service.
  3. A Service Control Handler (SCH), a function to communicate with the SCM.
  4. A Service Installer/Uninstaller, to register an EXE as a Service.

The Main Program

First, let us take a look at the main program of the Console application (it can also be a WinMain()).

#include "Winsvc.h"        //Header file for Services.

main()
{
  SERVICE_TABLE_ENTRY Table[]={{"Service1",ServiceMain},
                               {NULL,NULL}};
  StartServiceCtrlDispatcher(Table);
}

The only thing done by the main() is to fill a SERVICE_TABLE_ENTRY array. The position [0][0] contains the name of the Service (any string you like). Position [0][1] contains the name of the Service Main function; I specified it earlier in the list. It actually is a function pointer to the Service main function. The name can be anything. Now we start the first step to a service by calling StartServiceCtrlDispatcher() with the SERVICE_TABLE_ENTRY array. Note that the function signature should be that of the form. The [1][0] and [1][1] positions are NULL, just to mark the end of the array. (Not a must.) We can add more entries to the list if we have more than one service running from the same EXE.

The declaration of a typical ServiceMain() is as follows:

void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)

The ServiceMain Function

Now let us analyze our ServiceMain function. The main steps of this function are to:

  1. Fill the SERVICE_STATUS structure with appropriate values to communicate with the SCM.
  2. Register the Service Control Handler function mentioned earlier.
  3. Call the actual processing functions.

To proceed, we need two global variables here:

SERVICE_STATUS m_ServiceStatus;
SERVICE_STATUS_HANDLE m_ServiceStatusHandle;

The ServiceMain() can accept command-line arguments just as any C++ main() function. The first parameter contains the number of arguments being passed to the service. There will always be at least one argument. The second parameter is a pointer to an array of string pointers. The first item in the array always points to the service name. The SERVICE_STATUS data structure is used to fill the current state of the Service and notify it to the SCM. We use the API function SetServiceStatus() for the purpose. The data members of SERVICE_STATUS to look for are:

Data Member Name Description
dwServiceType SERVICE_WIN32  
dwCurrentState SERVICE_START_PENDING Trying To Start (Initially)
dwControlsAccepted SERVICE_ACCEPT_STOP Accepts Stop/Start only in Service control program. Usually in the control Panel (NT)/Administrative tools (2000). We can also set our service to accept PAUSE and CONTINUE functionality.

In the beginning of the ServiceMain(), we should set the dwCurrentState of SERVICE_STATUS to SERVICE_START_PENDING. This signals the SCM that the service is starting. If any error occurs along the way, we should notify the SCM by passing SERVICE_STOPPED. By default, the SCM will look for an activity from the service; if it fails to show any progress within two minutes, SCM kills that service.

The API function RegisterServiceCtrlHandler() is used to set the Service Control Handler Function of the Service with the SCM. The function takes two parameters as earlier, one service name (String) and the pointer to the Service Control Handler Function. That function should align with the signature.

Once we get here, we now set dwCurrentState as SERVICE_RUNNING to notify that the service has started to function. The next step is to call the actual processing steps.

The Service Control Handler Function

The Service Control Handler function is used by the SCM to communicate with the Service program about a user action on the service, such as a start, stop, pause, or continue. It basically contains a switch statement to deal with each case. Here we will call the appropriate steps to clean up and terminate the process. This function receives an opcode which can have values like SERVICE_CONTROL_PAUSE, SERVICE_CONTROL_CONTINUE, SERVICE_CONTROL_STOP, SERVICE_CONTROL_INTERROGATE, and so forth. We have to write appropriate steps on each.

Service Installer/Uninstaller

To install a service we need to make some entries in the system Registry. Windows has some APIs to do these steps, instead of using the Registry functions. They are CreateService() and DeleteService(). For both these functions we need to open the SCM database with the appropriate rights. I prefer using SC_MANAGER_ALL_ACCESS. To install a service, first open the SCM by using OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS). Then invoke CreateService() with the appropriate binary file path of our service. Here also we have to give the name of our service. We need this name if we want to delete a particular service. In deleting a service we need to open the specific service first by its name and then invoke DeleteService() on it. That’s all that we need. Take a look at the code given with it for more details.

Downloads

Download exe and cpp file – 32 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read