开发者

How to create service which restarts on crash

开发者 https://www.devze.com 2023-01-07 05:50 出处:网络
I am creating a service using CreateService. The service will run again fine if it happens to crash and I would like to have Windows restart the service if it crashes. I know it is possible to set thi

I am creating a service using CreateService. The service will run again fine if it happens to crash and I would like to have Windows restart the service if it crashes. I know it is possible to set this up from the services msc see below.

How to create service which restarts on crash

How can I prog开发者_StackOverflow中文版ramatically configure the service to always restart if it happens to crash.


Used Deltanine's approach, but modified it a bit to be able to control each failure action:

SERVICE_FAILURE_ACTIONS servFailActions;
SC_ACTION failActions[3];

failActions[0].Type = SC_ACTION_RESTART; //Failure action: Restart Service
failActions[0].Delay = 120000; //number of milliseconds to wait before performing failure action = 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


You want to call ChangeServiceConfig2 after you've installed the service. Set the second parameter to SERVICE_CONFIG_FAILURE_ACTIONS and pass in an instance of SERVICE_FAILURE_ACTIONS as the third parameter, something like this:

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


The answer above will give you the gist... but it wont compile.

try:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消