2010-07-14 29 views
9

Tôi đang tạo dịch vụ sử dụng CreateService. Dịch vụ sẽ chạy lại nếu nó xảy ra sự cố và tôi muốn Windows khởi động lại dịch vụ nếu nó bị treo. Tôi biết nó có thể thiết lập này từ các dịch vụ msc xem dưới đây.Cách tạo dịch vụ khởi động lại khi gặp sự cố

Windows Service Recovery Dialog

Làm thế nào tôi có thể programatically cấu hình dịch vụ để luôn luôn khởi động lại nếu nó xảy ra sụp đổ.

Trả lời

6

Bạn muốn gọi ChangeServiceConfig2 sau khi bạn đã cài đặt dịch vụ. Đặt tham số thứ hai để SERVICE_CONFIG_FAILURE_ACTIONS và vượt qua trong một thể hiện của SERVICE_FAILURE_ACTIONS như tham số thứ ba, một cái gì đó như thế này:

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

Câu trả lời ở trên sẽ cung cấp cho bạn những ý chính ... nhưng nó sẽ không biên dịch.

thử:

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

đã qua sử dụng cách tiếp cận Deltanine, nhưng sửa đổi nó một chút để có thể kiểm soát từng hành động thất bại:

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 
Các vấn đề liên quan