1、服务的主函数以及以及函数的声明,全局变量的定义
#define SERVICE_NAME "srv_follow" SERVICE_STATUS g_ServiceStatus; SERVICE_STATUS_HANDLE g_hServiceStatusHandle; void WINAPI service_main(int argc, char** argv); void WINAPI ServiceHandler(DWORD fdwControl);
//服务的主函数; int _tmain(int argc, _TCHAR* argv[]) { //设置服务程序所在的地址; TCHAR path[MAX_PATH] = {0}; GetModuleFileName(NULL,path,MAX_PATH); _stprintf(path,_T("%s//..//"),path); SetCurrentDirectory(path); //设置服务表; SERVICE_TABLE_ENTRY ServiceTable[2]; //设置服务到服务表; ServiceTable[0].lpServiceName = _T(SERVICE_NAME); ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)service_main; //表的最后元素必须为NULL; ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceProc = NULL; //服务分派到服务控制管理器; StartServiceCtrlDispatcher(ServiceTable); Logger::getInstance()->info(__FILE__,__LINE__,"StartServiceCtrlDispatcher success!"); DWORD err = GetLastError(); return 0; }
2、service_main函数
void WINAPI service_main(int argc, char** argv) { //SERVICE_WIN32_OWN_PROCESS g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING; g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwServiceSpecificExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; g_hServiceStatusHandle = RegisterServiceCtrlHandler(_T(SERVICE_NAME), ServiceHandler); if (g_hServiceStatusHandle==0) { DWORD nError = GetLastError(); } //add your init code here 这里是程序入口 // Initialization complete - report running status g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 9000; if(!SetServiceStatus(g_hServiceStatusHandle, &g_ServiceStatus)) { DWORD nError = GetLastError(); } }
3、ServiceHandler函数
void WINAPI ServiceHandler(DWORD fdwControl) { switch(fdwControl) { case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; //add you quit code here 这里释放资源 break; default: return; }; if (!SetServiceStatus(g_hServiceStatusHandle, &g_ServiceStatus)) { DWORD nError = GetLastError(); } }
以上就是把win32改为后台服务所需要的代码。