Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1804340
  • 博文数量: 290
  • 博客积分: 10653
  • 博客等级: 上将
  • 技术积分: 3178
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-24 23:08
文章存档

2013年(6)

2012年(15)

2011年(25)

2010年(86)

2009年(52)

2008年(66)

2007年(40)

分类: C/C++

2009-07-02 20:10:02

Writing a Service Program's main Function

The function of a service program calls the function to connect to the SCM and start the control dispatcher thread. The dispatcher thread loops, waiting for incoming control requests for the services specified in the dispatch table. This thread does not return until there is an error or all of the services in the process have terminated. When all services in a process have terminated, the SCM sends a control request to the dispatcher thread telling it to shut down. The thread can then return from the StartServiceCtrlDispatcher call and the process can terminate.

The following example is a service process that supports only one service. The SvcDebugOut function prints informational messages and errors to the debugger. It takes two parameters: a string that can contain one formatted output character and a numeric value to be used as the formatted character. For information on writing the MyServiceStart and MyServiceInitialization functions, see . For information on writing the MyServiceCtrlHandler function, see .

 

#include <windows.h>

SERVICE_STATUS MyServiceStatus;
SERVICE_STATUS_HANDLE MyServiceStatusHandle;

VOID SvcDebugOut(LPSTR String, DWORD Status);
VOID WINAPI MyServiceCtrlHandler (DWORD opcode);
VOID MyServiceStart (DWORD argc, LPTSTR *argv);
DWORD MyServiceInitialization (DWORD argc, LPTSTR *argv,
        DWORD *specificError);
 
void main( )
{
   SERVICE_TABLE_ENTRY DispatchTable[] =
   {
      { "MyService", MyServiceStart },
      { NULL, NULL }
   };
 
   if (!StartServiceCtrlDispatcher( DispatchTable))
   {
      SvcDebugOut(" [MY_SERVICE] StartServiceCtrlDispatcher (%d)\n",
         GetLastError());
   }
}
 
VOID SvcDebugOut(LPSTR String, DWORD Status)
{
   CHAR Buffer[1024];
   if (strlen(String) < 1000)
   {
      sprintf(Buffer, String, Status);
      OutputDebugStringA(Buffer);
   }
}

 

Writing a ServiceMain Function

The MyServiceStart function in the following example is the function for the service. MyServiceStart has access to the command-line arguments, in the way that the function of a console application does. 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 MyServiceStart function first fills in the structure including the control codes that it accepts. Although this service accepts SERVICE_CONTROL_PAUSE and SERVICE_CONTROL_CONTINUE, it does nothing significant when told to pause. SERVICE_ACCEPT_PAUSE_CONTINUE was included for illustration purposes only; if pausing does not add value to your service, do not support it.

The MyServiceStart function then calls the function to register MyService as the service's function and begin initialization. The following sample initialization function, MyServiceInitialization, is included for illustration purposes; it does not perform any initialization tasks such as creating additional threads. If your service's initialization performs tasks that are expected to take longer than one second, your code must call the function periodically to send out wait hints and check points indicating that progress is being made.

When initialization has completed successfully, the example calls SetServiceStatus with a status of SERVICE_RUNNING and the service continues with its work. If an error has occurred in initialization, MyServiceStart reports SERVICE_STOPPED with the SetServiceStatus function and returns.

Because this sample service does not complete any real tasks, MyServiceStart simply returns control to the caller. However, your service should use this thread to complete whatever tasks it was designed to do. If a service does not need a thread to do its work (such as a service that only processes RPC requests), its ServiceMain function should return control to the caller. It is important for the function to return, rather than call the function, because returning allows for cleanup of the memory allocated for the arguments.

You can provide for additional cleanup by calling the function on an event before returning. The thread that is running the ServiceMain function terminates, but the service itself continues to run. The service control handler can then signal your event when the service stops, and a thread from the thread pool executes your callback to perform any additional cleanup you need and to call SetServiceStatus with SERVICE_STOPPED. This technique is not illustrated in the sample code below, however.

To output debugging information, MyServiceStart calls SvcDebugOut. The source code for SvcDebugOut is given in .

 


#include <windows.h>

SERVICE_STATUS MyServiceStatus;
SERVICE_STATUS_HANDLE MyServiceStatusHandle;

VOID SvcDebugOut(LPSTR String, DWORD Status);

void WINAPI MyServiceStart (DWORD argc, LPTSTR *argv)
{
    DWORD status;
    DWORD specificError;
 
    MyServiceStatus.dwServiceType = SERVICE_WIN32;
    MyServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP |
        SERVICE_ACCEPT_PAUSE_CONTINUE;
    MyServiceStatus.dwWin32ExitCode = 0;
    MyServiceStatus.dwServiceSpecificExitCode = 0;
    MyServiceStatus.dwCheckPoint = 0;
    MyServiceStatus.dwWaitHint = 0;
 
    MyServiceStatusHandle = RegisterServiceCtrlHandler(
        "MyService",
        MyServiceCtrlHandler);
 
    if (MyServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
    {
        SvcDebugOut(" [MY_SERVICE] RegisterServiceCtrlHandler
            failed %d\n"
, GetLastError());
        return;
    }
 
    // Initialization code goes here.

    status = MyServiceInitialization(argc,argv, &specificError);
 
    // Handle error condition

    if (status != NO_ERROR)
    {
        MyServiceStatus.dwCurrentState = SERVICE_STOPPED;
        MyServiceStatus.dwCheckPoint = 0;
        MyServiceStatus.dwWaitHint = 0;
        MyServiceStatus.dwWin32ExitCode = status;
        MyServiceStatus.dwServiceSpecificExitCode = specificError;
 
        SetServiceStatus (MyServiceStatusHandle, &MyServiceStatus);
        return;
    }
 
    // Initialization complete - report running status.

    MyServiceStatus.dwCurrentState = SERVICE_RUNNING;
    MyServiceStatus.dwCheckPoint = 0;
    MyServiceStatus.dwWaitHint = 0;
 
    if (!SetServiceStatus (MyServiceStatusHandle, &MyServiceStatus))
    {
        status = GetLastError();
        SvcDebugOut(" [MY_SERVICE] SetServiceStatus error
            %ld\n"
,status);
    }
 
    // This is where the service does its work.

    SvcDebugOut(" [MY_SERVICE] Returning the Main Thread \n",0);
 
    return;
}
 
// Stub initialization function.

DWORD MyServiceInitialization(DWORD argc, LPTSTR *argv,
    DWORD *specificError)
{
    argv;
    argc;
    specificError;
    return(0);
}
 

阅读(855) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~