如何创建在崩溃时重新启动的服务

时间:2010-07-14 00:15:20

标签: c++ windows winapi service

我正在使用CreateService创建服务。如果崩溃发生,该服务将再次运行良好,我希望Windows重新启动服务,如果它崩溃。我知道可以从服务msc中设置它,见下文。

Windows Service Recovery Dialog

我如何以编程方式将服务配置为在崩溃时始终重新启动。

3 个答案:

答案 0 :(得分:10)

使用Deltanine的方法,但稍微修改了一下以便能够控制每个失败动作:

SERVICE_FAILURE_ACTIONS servFailActions;
SC_ACTION failActions[3];

failActions[0].Type = SC_ACTION_RESTART; //Failure action: Restart Service
failActions[0].Delay = 120000; //number of seconds to wait before performing failure action, in milliseconds = 2minutes
failActions[1].Type = SC_ACTION_RESTART;
failActions[1].Delay = 120000;
failActions[2].Type = SC_ACTION_NONE;
failActions[2].Delay = 120000;

servFailActions.dwResetPeriod = 86400; // Reset Failures Counter, in Seconds = 1day
servFailActions.lpCommand = NULL; //Command to perform due to service failure, not used
servFailActions.lpRebootMsg = NULL; //Message during rebooting computer due to service failure, not used
servFailActions.cActions = 3; // Number of failure action to manage
servFailActions.lpsaActions = failActions;

ChangeServiceConfig2(sc_service, SERVICE_CONFIG_FAILURE_ACTIONS, &servFailActions); //Apply above settings

答案 1 :(得分:8)

您希望在安装服务后致电ChangeServiceConfig2。将第二个参数设置为SERVICE_CONFIG_FAILURE_ACTIONS并传入SERVICE_FAILURE_ACTIONS的实例作为第三个参数,如下所示:

int numBytes = sizeof(SERVICE_FAILURE_ACTIONS) + sizeof(SC_ACTION);
std::vector<char> buffer(numBytes);

SERVICE_FAILURE_ACTIONS *sfa = reinterpret_cast<SERVICE_FAILURE_ACTIONS *>(&buffer[0]);
sfa.dwResetPeriod = INFINITE;
sfa.cActions = 1;
sfa.lpsaActions[0].Type = SC_ACTION_RESTART;
sfa.lpsaActions[0].Delay = 5000; // wait 5 seconds before restarting

ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, sfa);

答案 2 :(得分:4)

上面的答案会给你一个要点......但它不会编译。

尝试:

SERVICE_FAILURE_ACTIONS sfa;
SC_ACTION actions;

sfa.dwResetPeriod = INFINITE;
sfa.lpCommand = NULL;
sfa.lpRebootMsg = NULL;
sfa.cActions = 1;
sfa.lpsaActions = &actions;

sfa.lpsaActions[0].Type = SC_ACTION_RESTART;
sfa.lpsaActions[0].Delay = 5000; 

ChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfa)