Click here to Skip to main content
15,861,172 members
Articles / Desktop Programming / Win32

Simple Windows Service in C++

Rate me:
Please Sign up or sign in to vote.
4.92/5 (90 votes)
30 May 2013CPOL3 min read 429.3K   27.7K   181   64
An article that shows how to create a simple Windows service in C++.

Introduction

This article shows how to create a basic Windows Service in C++. Services are very useful in many development scenarios depending on the architecture of the application.

Background

There are not many Windows Service examples that I found in C++. I used MSDN to write this very basic Windows service.

Using the code

At a minimum a service requires the following items:

  • A Main Entry point (like any application)
  • A Service Entry point
  • A Service Control Handler

You can use a Visual Studio template project to help you get started. I just created an "Empty" Win32 Console Application.

Before we get started on the Main Entry Point, we need to declare some globals that will be used throughout the service. To be more object oriented you can always create a class that represents your service and use class members instead of globals. To keep it simple I will use globals.

We will need a SERVICE_STATUS structure that will be used to report the status of the service to the Windows Service Control Manager (SCM).

C++
SERVICE_STATUS        g_ServiceStatus = {0}; 

We will also need a SERVICE_STATUS_HANDLE that is used to reference our service instance once it is registered with the SCM.

C++
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;

Here are some additional globals and function declarations that will be used and explained as we go along.

C++
SERVICE_STATUS        g_ServiceStatus = {0};
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE                g_ServiceStopEvent = INVALID_HANDLE_VALUE;
 
VOID WINAPI ServiceMain (DWORD argc, LPTSTR *argv);
VOID WINAPI ServiceCtrlHandler (DWORD);
DWORD WINAPI ServiceWorkerThread (LPVOID lpParam);
 
#define SERVICE_NAME  _T("My Sample Service")    

Main Entry Point

C++
int _tmain (int argc, TCHAR *argv[])
{
    SERVICE_TABLE_ENTRY ServiceTable[] = 
    {
        {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
        {NULL, NULL}
    };
 
    if (StartServiceCtrlDispatcher (ServiceTable) == FALSE)
    {
        return GetLastError ();
    }
 
    return 0;
}

In the main entry point you quickly call StartServiceCtrlDispatcher so the SCM can call your Service Entry point (ServiceMain in the example above). You want to defer any initialization until your Service Entry point, which is defined next.

Service Entry Point

C++
VOID WINAPI ServiceMain (DWORD argc, LPTSTR *argv)
{
    DWORD Status = E_FAIL;
 
    // Register our service control handler with the SCM
    g_StatusHandle = RegisterServiceCtrlHandler (SERVICE_NAME, ServiceCtrlHandler);
 
    if (g_StatusHandle == NULL) 
    {
        goto EXIT;
    }
 
    // Tell the service controller we are starting
    ZeroMemory (&g_ServiceStatus, sizeof (g_ServiceStatus));
    g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwControlsAccepted = 0;
    g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;
 
    if (SetServiceStatus (g_StatusHandle , &g_ServiceStatus) == FALSE)
    {
        OutputDebugString(_T(
          "My Sample Service: ServiceMain: SetServiceStatus returned error"));
    }
 
    /*
     * Perform tasks necessary to start the service here
     */
 
    // Create a service stop event to wait on later
    g_ServiceStopEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
    if (g_ServiceStopEvent == NULL) 
    {   
        // Error creating event
        // Tell service controller we are stopped and exit
        g_ServiceStatus.dwControlsAccepted = 0;
        g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
        g_ServiceStatus.dwWin32ExitCode = GetLastError();
        g_ServiceStatus.dwCheckPoint = 1;
 
        if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
	{
	    OutputDebugString(_T(
	      "My Sample Service: ServiceMain: SetServiceStatus returned error"));
	}
        goto EXIT; 
    }    
    
    // Tell the service controller we are started
    g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
    g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;
 
    if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
    {
        OutputDebugString(_T(
          "My Sample Service: ServiceMain: SetServiceStatus returned error"));
    }
 
    // Start a thread that will perform the main task of the service
    HANDLE hThread = CreateThread (NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
   
    // Wait until our worker thread exits signaling that the service needs to stop
    WaitForSingleObject (hThread, INFINITE);
   
    
    /*
     * Perform any cleanup tasks 
     */
 
    CloseHandle (g_ServiceStopEvent);
 
    // Tell the service controller we are stopped
    g_ServiceStatus.dwControlsAccepted = 0;
    g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 3;
 
    if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
    {
        OutputDebugString(_T(
          "My Sample Service: ServiceMain: SetServiceStatus returned error"));
    }
    
EXIT:
    return;
} 

The Service Main Entry Point performs the following tasks:

  • Initialize any necessary items which we deferred from the Main Entry Point.
  • Register the service control handler which will handle Service Stop, Pause, Continue, Shutdown, etc control commands. These are registered via the dwControlsAccepted field of the SERVICE_STATUS structure as a bit mask.
  • Set Service Status to SERVICE_PENDING then to SERVICE_RUNNING. Set status to SERVICE_STOPPED on any errors and on exit. Always set SERVICE_STATUS.dwControlsAccepted to 0 when setting status to SERVICE_STOPPED or SERVICE_PENDING.
  • Perform start up tasks. Like creating threads/events/mutex/IPCs/etc.

Service Control Handler

C++
VOID WINAPI ServiceCtrlHandler (DWORD CtrlCode)
{
    switch (CtrlCode) 
	{
     case SERVICE_CONTROL_STOP :
 
        if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
           break;
 
        /* 
         * Perform tasks necessary to stop the service here 
         */
        
        g_ServiceStatus.dwControlsAccepted = 0;
        g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCheckPoint = 4;
 
        if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
        {
            OutputDebugString(_T(
              "My Sample Service: ServiceCtrlHandler: SetServiceStatus returned error"));
        }
 
        // This will signal the worker thread to start shutting down
        SetEvent (g_ServiceStopEvent);
 
        break;
 
     default:
         break;
    }
}  

The Service Control Handler was registered in your Service Main Entry point. Each service must have a handler to handle control requests from the SCM. The control handler must return within 30 seconds or the SCM will return an error stating that the service is not responding. This is because the handler will be called in the context of the SCM and will hold the SCM until it returns from the handler.

I have only implemented and supported the SERVICE_CONTROL_STOP request. You can handle other requests such as SERVICE_CONTROL_CONTINUE, SERVICE_CONTROL_INTERROGATE, SERVICE_CONTROL_PAUSE, SERVICE_CONTROL_SHUTDOWN and others supported by the Handler or HandlerEx function that can be registered with the RegisterServiceCtrlHandler(Ex) function.

Service Worker Thread

C++
DWORD WINAPI ServiceWorkerThread (LPVOID lpParam)
{
    //  Periodically check if the service has been requested to stop
    while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0)
    {        
        /* 
         * Perform main service function here
         */
 
        //  Simulate some work by sleeping
        Sleep(3000);
    }
 
    return ERROR_SUCCESS;
} 

This sample Service Worker Thread does nothing but sleep and check to see if the service has received a control to stop. Once a stop control has been received the Service Control Handler sets the g_ServiceStopEvent event. The Service Worker Thread breaks and exits. This signals the Service Main routine to return and effectively stop the service.

Installing the Service

You can install the service from the command prompt by running the following command:

C:\>sc create "My Sample Service" binPath= C:\SampleService.exe

A space is required between binPath= and the value[?]. Also, use the full absolute path to the service executable.

You should now see the service in the Windows Services console. From here you can start and stop the service.

Uninstalling the Service

You can uninstall the service from the command prompt by running the following command:

C:\>sc delete "My Sample Service"  

History

  • 11/28/2012: Initial release of article and code.
  • 11/29/2012: Improved code and fixed one typo in article sample code.
  • 11/03/2015: Updated details on how to install the service based on user comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionYou seem to forget to close the handle of the worker thread Pin
SMDtheone19-Jul-23 7:18
SMDtheone19-Jul-23 7:18 
QuestionOPEN NOTE PAD IF SERVICE RUNS Pin
sahil ajmeri 202216-Mar-23 0:42
sahil ajmeri 202216-Mar-23 0:42 
QuestionCould I compile it at Realsense 64 bit configuraiton? Pin
Member 992670913-May-22 21:38
Member 992670913-May-22 21:38 
AnswerRe: Could I compile it at Realsense 64 bit configuraiton? Pin
Member 992670913-May-22 21:47
Member 992670913-May-22 21:47 
QuestionWhat is the difference vs. ANSI C and the C++ code in here? Pin
DBJDBJ2-Jan-22 23:56
DBJDBJ2-Jan-22 23:56 
QuestionThank you for the sample Pin
Andrey Novik1-Jun-21 9:40
Andrey Novik1-Jun-21 9:40 
GeneralMy vote of 5 Pin
Andrey Novik1-Jun-21 9:38
Andrey Novik1-Jun-21 9:38 
QuestionCan't start service Pin
Member 1502224815-Dec-20 19:44
Member 1502224815-Dec-20 19:44 
AnswerRe: Can't start service Pin
Bram Stolk24-Dec-21 9:30
Bram Stolk24-Dec-21 9:30 
QuestionAdding a description Pin
Paul Belikian5-Jul-20 7:36
Paul Belikian5-Jul-20 7:36 
QuestionSimple C++ WIn service Pin
HolySpirit_OM19-Mar-20 13:11
HolySpirit_OM19-Mar-20 13:11 
QuestionModify for open notepad everytime system boot Pin
AnduinBrian2-Oct-19 21:49
AnduinBrian2-Oct-19 21:49 
Questionstart service automatically Pin
Member 1450272119-Jun-19 2:50
Member 1450272119-Jun-19 2:50 
GeneralMy vote of 4 Pin
hgfernan5-Oct-18 6:30
hgfernan5-Oct-18 6:30 
QuestionService not starting Pin
Member 1380132527-Apr-18 2:14
Member 1380132527-Apr-18 2:14 
AnswerRe: Service not starting Pin
Jetteroh8-May-18 4:27
Jetteroh8-May-18 4:27 
Question1053 error when trying to start the service Pin
Member 1093793213-Apr-18 5:38
Member 1093793213-Apr-18 5:38 
AnswerRe: 1053 error when trying to start the service Pin
nemesisv2-Sep-18 23:31
nemesisv2-Sep-18 23:31 
GeneralRe: 1053 error when trying to start the service Pin
Member 1131380118-Oct-18 11:02
Member 1131380118-Oct-18 11:02 
QuestionHow stop and start action in code? Pin
Member 136957039-Apr-18 3:54
Member 136957039-Apr-18 3:54 
Suggestion[My vote of 1] Not for beginners Pin
Member 1329809411-Jul-17 1:55
Member 1329809411-Jul-17 1:55 
SuggestionPlease include the #include's in the article PinPopular
Member 1114174722-Feb-17 10:32
Member 1114174722-Feb-17 10:32 
QuestionService Status Pin
anmol27016-Oct-16 22:29
professionalanmol27016-Oct-16 22:29 
QuestionApplication Pin
alan935-Sep-16 8:25
alan935-Sep-16 8:25 
QuestionThank you Sir! Pin
Member 1116586720-Aug-16 10:25
Member 1116586720-Aug-16 10:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.