views:

729

answers:

4

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.

+1  A: 

Hope this helps:

http://support.microsoft.com/kb/251192

It would seem that you simple need to run this exe against a binary executable to register it as a service.

Nick Berardi
+1  A: 

Basically there are some registry settings you have to set as well as some interfaces to implement.

Check out this: http://msdn.microsoft.com/en-us/library/ms685141.aspx

You are interested in the SCM (Service Control Manager).

Daren Thomas
+3  A: 

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;
}
Ferruccio
+1  A: 

I know I'm a bit late to the party, but I've recently had this same question, and had to struggle through the interwebs looking for answers.

I managed to find this article in MSDN that does in fact lay the groundwork. I ended up combining many of the files here into a single exe that contains all of the commands I need, and added in my own "void run()" method that loops for the entirely life of the service for my own needs.

This would be a great start to someone else with exactly this question, so for future searchers out there, check it out:

The Complete Service Sample http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx

KevenK