C++ 编写Windows service
最近实现一个windows server端守护进程启动服务功能(c++实现),遇到了一些问题,记录一下
1. 启动Service实现代码:
1 int _tmain(int argc, TCHAR* argv[]) 2 { 3 SERVICE_TABLE_ENTRYW dispatch_table[] = { 4 { gServiceName, (LPSERVICE_MAIN_FUNCTIONW)serviceMain }, 5 { NULL, NULL } 6 }; 7 8 if (!StartServiceCtrlDispatcherW(dispatch_table)) 9 { 10 svcReportEvent(TEXT("StartServiceCtrlDispatcherW Error!")); 11 gadgetLogWrite(NULL, "StartServiceCtrlDispatcherW Error!"); 12 } 13 }
1 void WINAPI serviceMain(DWORD argc, LPTSTR *argv) 2 { 3 gSvcStatusHandle = RegisterServiceCtrlHandlerW(gServiceName, 4 service_ctrl_handler); 5 6 if (IS_INVALID_HANDLE(gSvcStatusHandle)) 7 { 8 gadgetLogWrite(NULL, "Failed to register Service Control for %S", gServiceName); 9 return; 10 } 11 }
需要注意的是本地调试的时候,是无法获得ServiceCtrlHandler,必须要在系统服务里直接调用,所以测试打印一定要做好