Writing a Service Program's main Function

Writing a Service Program's main Function

The main function of a service program calls the StartServiceCtrlDispatcher 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 Writing a ServiceMain Function. For information on writing the MyServiceCtrlHandler function, see Writing a Control Handler Function.

#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); 
   } 
}

If your service program supports multiple services, the implementation of the main function will differ slightly. The names of the additional services should be added to the dispatch table so they can be monitored by the dispatcher thread.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值