目标:
1. 实现配置后台服务,使其自动启动。
2. 当程序down后,会自动启动。
/*主要流程*/
1. 判断是否已经是服务在运行(argv)
2. 如果是第一次执行,初始化服务:
SC_HANDLE sc_handle=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(sc_handle==NULL)
{
printf("OpenSCManager 安装失败\n");
return -1;
}
char filename[1024]={0};
//获取当前的绝对路径:
::GetModuleFileName(NULL,filename,1024);
cout<<"GetModuleFileName:"<<filename<<endl;
SC_HANDLE ret;
//LPCTSTR
ret=CreateService(sc_handle,SEVICE_NAME,SEVICE_NAME,SC_MANAGER_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,filename,NULL,NULL,"", NULL,NULL);
if(ret==NULL)
{
DWORD errcode=::GetLastError();
cout<<errcode<<endl;
printf("CreateService 安装失败\n");
return -1;
}
3. 配置服务的自动运行:
SC_ACTION act[3];
SERVICE_FAILURE_ACTIONS sfa;
//First failure:
act[0].Delay = 60 * 1000; // wait 60 seconds before restarting
act[0].Type = SC_ACTION_RESTART;
//Second failure:
act[1].Delay = 60 * 1000;
act[1].Type = SC_ACTION_RESTART;
//Subsequent failure:
act[2].Delay = 60 * 1000;
act[2].Type = SC_ACTION_RESTART;
sfa.lpRebootMsg = NULL;
sfa.lpsaActions = act;
sfa.dwResetPeriod = 3600*24; // Reset the error count after 1day
sfa.lpCommand = NULL;
sfa.cActions = 3;
int ret = ChangeServiceConfig2(schService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfa);
if (ret == 0)
{
printf("setServiceRecovery 设置自动重启失败: ");
DWORD errcode=::GetLastError();
cout<<errcode<<endl;
}
else
{
printf("设置自动重启成功\n");
}
4. 执行服务:
printf("服务注册成功\n");
if(::StartService(ret,NULL,NULL)==NULL)
{
printf("程序启动服务失败,请手动启动agent服务\n");
}
/*接下来不是第一次启动的话*/
5. 重定向启动函数:
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{SEVICE_NAME,Service::CmdStart},
{NULL ,NULL }
};
6. 正式启动:
StartServiceCtrlDispatcher(DispatchTable);