后台服务程序的创建:
以下例子中创建了两个服务,分别为 “service1” "service2"
#include "stdio.h"
#include "afx.h"
int main(int argc, char* argv[])
{
SC_HANDLE schSCManager;
CString strPath = "C://Multi_services.exe" ;
// Open a handle to the SC Manager database.
schSCManager = OpenSCManager(
NULL, // local machine
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
printf("OpenSCManager failed (%d)/n", GetLastError());
HANDLE hService = CreateService(
schSCManager,
"service1",
"service1",
SERVICE_ALL_ACCESS,
SERVICE_WIN32_SHARE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
strPath,
NULL, NULL, NULL, NULL, NULL);
HANDLE hService = CreateService(
schSCManager,
"service2",
"service2",
SERVICE_ALL_ACCESS,
SERVICE_WIN32_SHARE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
strPath,
NULL, NULL, NULL, NULL, NULL);
printf("getlasterror():%d/n",GetLastError());
StartServiceW(hService,0,NULL);
printf("getlasterror():%d",GetLastError());
return 0;
}
服务程序部分:
void main(int argc, char** argv)
{
SERVICE_TABLE_ENTRY ServiceTable[3];
ServiceTable[0].lpServiceName = "service1";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)Service1Main;
ServiceTable[1].lpServiceName = "service2";
ServiceTable[1].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)Service2Main;
ServiceTable[2].lpServiceName = NULL;
ServiceTable[2].lpServiceProc = NULL;
int i = StartServiceCtrlDispatcher(ServiceTable);
return;
}
void Service1Main(int argc, char** argv)
{
ServiceStatus.dwServiceType =
SERVICE_WIN32_SHARE_PROCESS;
ServiceStatus.dwCurrentState =
SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted =
SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler(
"Service1",
(LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
return;
}
// We report the running status to SCM.
}
void Service2Main(int argc,char**argv)
{
SetTimeServicStatus.dwServiceType =
SERVICE_WIN32_SHARE_PROCESS;
SetTimeServicStatus.dwCurrentState =
SERVICE_START_PENDING;
SetTimeServicStatus.dwControlsAccepted =
SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_SHUTDOWN;
SetTimeServicStatus.dwWin32ExitCode = 0;
SetTimeServicStatus.dwServiceSpecificExitCode = 0;
SetTimeServicStatus.dwCheckPoint = 0;
SetTimeServicStatus.dwWaitHint = 0;
hSetTimeStatus = RegisterServiceCtrlHandler(
"Service2",
(LPHANDLER_FUNCTION)SetTimeControlHandler);
SetTimeServicStatus.dwCurrentState = SERVICE_STOP;
SetServiceStatus (hSetTimeStatus, &SetTimeServicStatus);
while (ServiceStatus.dwCurrentState ==SERVICE_RUNNING)
{
}
return ;
}