Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Windows service without Visual Studio

So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.

like image 867
C Hogg Avatar asked Sep 03 '08 13:09

C Hogg


1 Answers

Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).

The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.

ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.

Here are some snippets from a service I wrote a few years ago:

set up as service:

SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
   { "ServiceName", ServiceMain },
   { 0, 0 }
};

if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
   DWORD err = GetLastError();
   if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
      return false;
}

ServiceMain:

void WINAPI ServiceMain(DWORD, LPTSTR*)
{
    hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);

service handler:

DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
    switch (ControlCode)
    {
    case SERVICE_CONTROL_INTERROGATE :
        // update OS about our status
    case SERVICE_CONTROL_STOP :
        // shut down service
    }

    return 0;
}
like image 94
Ferruccio Avatar answered Sep 25 '22 08:09

Ferruccio