static void WINAPI ServiceMain( DWORD dwArgc, LPTSTR *lpszArgv ) { WTS_SESSION_INFO *pInfos; DWORD count; if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE,NULL,1,&pInfos,&count)) { for (DWORD i=0;i<count;i++) { LogText("Session %d (%d)\n",pInfos[i].SessionId,pInfos[i].State); if (pInfos[i].State==WTSActive) { StartStartMenu(pInfos[i].SessionId); } } WTSFreeMemory(pInfos); } g_hServiceStatus=RegisterServiceCtrlHandlerEx(g_ServiceName,ServiceHandlerEx,NULL); if (g_hServiceStatus) { g_ServiceStatus.dwServiceType=SERVICE_WIN32; g_ServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_PAUSE_CONTINUE|SERVICE_ACCEPT_SESSIONCHANGE; g_ServiceStatus.dwWin32ExitCode=0; g_ServiceStatus.dwServiceSpecificExitCode=0; g_ServiceStatus.dwCurrentState=SERVICE_RUNNING; g_ServiceStatus.dwCheckPoint=0; g_ServiceStatus.dwWaitHint=0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); } }
void WINAPI CW32Service::_serviceMain(DWORD dwArgc, char** lpszArgv) { stSvcStatus* pStatus = FindServiceStatus(lpszArgv[0]); CW32Service* pService = pStatus->pServiceObj; pStatus->status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; pStatus->status.dwCurrentState = SERVICE_START_PENDING; pStatus->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; pStatus->status.dwWin32ExitCode = 0; pStatus->status.dwServiceSpecificExitCode = 0; pStatus->status.dwCheckPoint = 0; pStatus->status.dwWaitHint = 0; // register the service control handler if ( !(pStatus->statusHandle = RegisterServiceCtrlHandlerEx( pStatus->lpszServiceName, _serviceHandler, pStatus )) ) return; // call the initialisation function (if stipulated) if ( pStatus->lpInitProc ) pStatus->lpInitProc((void*)pStatus); // now we can run the service... ;) YAY!! pStatus->status.dwCurrentState = SERVICE_RUNNING; pStatus->status.dwCheckPoint = 0; pStatus->status.dwWaitHint = 0; SetServiceStatus( pStatus->statusHandle, &pStatus->status ); }
// // Purpose: // Entry point for the service // // Parameters: // dwArgc - Number of arguments in the lpszArgv array // lpszArgv - Array of strings. The first string is the name of // the service and subsequent strings are passed by the process // that called the StartService function to start the service. // // Return value: // None. // VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv ) { // Register the handler function for the service gSvcStatusHandle = RegisterServiceCtrlHandlerEx( SVCNAME, SvcCtrlHandler, NULL); if( !gSvcStatusHandle ) { LbtReportFunctionError(TEXT("RegisterServiceCtrlHandler")); return; } // These SERVICE_STATUS members remain as set here gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; gSvcStatus.dwServiceSpecificExitCode = 0; // Report initial status to the SCM ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 ); // Perform service-specific initialization and work. SvcInit( dwArgc, lpszArgv ); }
VOID WINAPI service_main(DWORD argc, TCHAR *argv[]) { GAService *service = &ga_state->service; service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME, service_ctrl_handler, NULL); if (service->status_handle == 0) { g_critical("Failed to register extended requests function!\n"); return; } service->status.dwServiceType = SERVICE_WIN32; service->status.dwCurrentState = SERVICE_RUNNING; service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; service->status.dwWin32ExitCode = NO_ERROR; service->status.dwServiceSpecificExitCode = NO_ERROR; service->status.dwCheckPoint = 0; service->status.dwWaitHint = 0; SetServiceStatus(service->status_handle, &service->status); g_main_loop_run(ga_state->main_loop); service->status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(service->status_handle, &service->status); }
VOID WINAPI ServiceMain(DWORD argc, LPTSTR argv[]) { SERVICEINFO servInfo; LogEvent(_T("Entering ServiceMain"), 0, 0, LOG_FILE); servInfo.servStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; servInfo.servStatus.dwCurrentState = SERVICE_STOPPED; servInfo.servStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE; servInfo.servStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; servInfo.servStatus.dwServiceSpecificExitCode = 0; servInfo.servStatus.dwCheckPoint = 0; servInfo.servStatus.dwWaitHint = 1000; LogEvent(_T("Registering service control handler"), 0, 0, LOG_FILE); servInfo.hStatus = RegisterServiceCtrlHandlerEx(ServiceName, ServerCtrlHandler, &servInfo); if (!servInfo.hStatus) LogEvent(_T("Failed to register service"), GetLastError(), 100, LOG_ALL); UpdateStatus(&servInfo, SERVICE_START_PENDING, 1); if (!CreateServiceThread(&servInfo)) { servInfo.servStatus.dwServiceSpecificExitCode = 1; UpdateStatus(&servInfo, SERVICE_STOPPED, 0); return; } LogEvent(_T("Service thread shut down. Set SERVICE_STOPPED status"), 0, 0, LOG_FILE); UpdateStatus(&servInfo, SERVICE_STOPPED, 0); LogEvent(_T("Leaving ServiceMain"), 0, 0, LOG_FILE); }
static void WINAPI vboxServiceWinMain(DWORD argc, LPTSTR *argv) { VBoxServiceVerbose(2, "Registering service control handler ...\n"); #ifdef TARGET_NT4 g_hWinServiceStatus = RegisterServiceCtrlHandler(VBOXSERVICE_NAME, vboxServiceWinCtrlHandler); #else g_hWinServiceStatus = RegisterServiceCtrlHandlerEx(VBOXSERVICE_NAME, vboxServiceWinCtrlHandler, NULL); #endif if (g_hWinServiceStatus != NULL) { VBoxServiceVerbose(2, "Service control handler registered.\n"); vboxServiceWinStart(); } else { DWORD dwErr = GetLastError(); switch (dwErr) { case ERROR_INVALID_NAME: VBoxServiceError("Invalid service name!\n"); break; case ERROR_SERVICE_DOES_NOT_EXIST: VBoxServiceError("Service does not exist!\n"); break; default: VBoxServiceError("Could not register service control handle! Error: %ld\n", dwErr); break; } } }
//Add info about service and run core of GladBack void ServiceMain() { Status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; Status.dwCurrentState = SERVICE_START_PENDING; Status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; Status.dwWin32ExitCode = 0; Status.dwServiceSpecificExitCode = 0; Status.dwCheckPoint = 0; Status.dwWaitHint = 0; hStatus = RegisterServiceCtrlHandlerEx(SERVICE_NAME, (LPHANDLER_FUNCTION_EX)ControlHandler, 0); if(hStatus == (SERVICE_STATUS_HANDLE)0) return; Status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(hStatus, &Status); // Run сore of GladBack QCoreApplication app(ARGC, ARGV); ZBC_GB_Core sysCore; sysCore.run(); app.exec(); while(1); }
int service_init(LPHANDLER_FUNCTION_EX handler) { int rc; _service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; _service_status.dwCurrentState = SERVICE_STOPPED; _service_status.dwControlsAccepted = 0; _service_status.dwWin32ExitCode = NO_ERROR; _service_status.dwServiceSpecificExitCode = NO_ERROR; _service_status.dwCheckPoint = 0; _service_status.dwWaitHint = 0; _service_status_handle = RegisterServiceCtrlHandlerEx(_service_name, handler, NULL); if (_service_status_handle == 0) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); log_error("Could not register service control handler: %s (%d)", get_errno_name(rc), rc); return -1; } return 0; }
VOID WINAPI run_service(DWORD argc, LPTSTR* argv) { int err = 1; extern int main2(int argc, char **argv); status.dwServiceType = SERVICE_WIN32; status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; status.dwWin32ExitCode = 0; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 0; statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); if (!statushandle) { logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError())); err = 1; } else { status.dwWaitHint = 30000; status.dwCurrentState = SERVICE_START_PENDING; SetServiceStatus(statushandle, &status); status.dwWaitHint = 0; status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(statushandle, &status); err = main2(argc, argv); status.dwWaitHint = 0; status.dwCurrentState = SERVICE_STOPPED; //status.dwWin32ExitCode = err; SetServiceStatus(statushandle, &status); } return; }
/* this is the main function of the service. when this function returns the * service will be terminated by the SCM */ void WINAPI ServiceMain(DWORD argc, PTSTR *argv) { SERVICE_STATUS *pSt = &ctx->status; /* register the service with the ServiceControlManager */ ctx->hServiceStatus = RegisterServiceCtrlHandlerEx(ss_name, HandlerEx, ctx); dbg_err_if( ctx->hServiceStatus == 0 ); /* init the status struct and update the service status */ ZeroMemory(pSt, sizeof(SERVICE_STATUS)); /* just one service in this exe */ pSt->dwServiceType = SERVICE_WIN32_OWN_PROCESS; /* action supported by the service */ pSt->dwControlsAccepted = SERVICE_ACCEPT_STOP; /* error returned while starting/stopping */ pSt->dwWin32ExitCode = NO_ERROR; /* service specific exit code */ pSt->dwServiceSpecificExitCode = 0; /* we're still initializing */ pSt->dwCurrentState = SERVICE_START_PENDING; /* for progress operation */ pSt->dwCheckPoint = 1; /* wait hint */ pSt->dwWaitHint = 1000; /* set status */ dbg_err_if(SetServiceStatus(ctx->hServiceStatus, pSt) == 0); dbg_err_if(parse_opt(argc, argv)); /* load config and initialize */ dbg_err_if(app_init()); /* this should happen after initialization but I don't want to mess main.c with win32-only code */ /* notify the end of initialization */ u_dbg("SERVICE_RUNNING"); ctx->status.dwCurrentState = SERVICE_RUNNING; ctx->status.dwCheckPoint = ctx->status.dwWaitHint = 0; dbg_err_if(!SetServiceStatus(ctx->hServiceStatus, &ctx->status)); /* run the main loop */ app_run(); /* let the service terminate */ ctx->status.dwCurrentState = SERVICE_STOPPED; dbg_err_if(!SetServiceStatus(ctx->hServiceStatus, &ctx->status)); return; err: warn_strerror(GetLastError()); /* let the service terminate */ ctx->status.dwCurrentState = SERVICE_STOPPED; dbg_err_if(!SetServiceStatus(ctx->hServiceStatus, &ctx->status)); }
VOID WINAPI ServiceMain(_In_ DWORD dwArgc, _In_ LPTSTR *lpszArgv) { svc_baton *baton = find_baton(lpszArgv[0]); baton->status_handle = RegisterServiceCtrlHandlerEx(baton->name, HandlerEx, baton); baton->dwArgc = dwArgc; baton->lpszArgv = lpszArgv; uv_async_send(&baton->svc_async_handle); WaitForSingleObject(baton->svc_end_event, INFINITE); }
static void WINAPI service_main(DWORD argc, char **argv) { zend_win32service_globals *g = (zend_win32service_globals*)tmp_service_g; OSVERSIONINFO osvi; DWORD base_priority; HKEY hKey; char *service_key; long registry_result = ERROR_SUCCESS; DWORD dwType = REG_DWORD; DWORD dwSize = sizeof(DWORD); /* Get the current OS version. */ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); // Set the base priority for this service. spprintf(&service_key, 0, "%s%s", SERVICES_REG_KEY_ROOT, g->service_name); registry_result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, service_key, 0, KEY_ALL_ACCESS, &hKey); if (ERROR_SUCCESS == registry_result) { registry_result = RegQueryValueEx(hKey, SERVICES_REG_BASE_PRIORITY, 0, &dwType, (LPBYTE)&base_priority, &dwSize); } efree(service_key); if (hKey) { RegCloseKey(hKey); } if (ERROR_SUCCESS != registry_result) { g->code = registry_result; SetEvent(g->event); return; } if(!SetPriorityClass(GetCurrentProcess(), base_priority)) { g->code = GetLastError(); SetEvent(g->event); return; } g->st.dwServiceType = SERVICE_WIN32; g->st.dwCurrentState = SERVICE_START_PENDING; g->st.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE | (osvi.dwMajorVersion >= 6 ? SERVICE_ACCEPT_PRESHUTDOWN : 0); /* Allow the service to be paused and handle Vista-style pre-shutdown notifications. */ g->sh = RegisterServiceCtrlHandlerEx(g->service_name, service_handler, g); if (g->sh == (SERVICE_STATUS_HANDLE)0) { g->code = GetLastError(); SetEvent(g->event); return; } g->code = NO_ERROR; SetEvent(g->event); }
void ServiceStatus::Initialize(LPCWSTR serviceName, LPHANDLER_FUNCTION_EX handlerFunction, PVOID pvContext) { m_ssh = RegisterServiceCtrlHandlerEx(serviceName, handlerFunction, pvContext); //exception dwServiceType = SERVICE_WIN32_OWN_PROCESS; dwCurrentState = SERVICE_START_PENDING; dwControlsAccepted = 0; dwWin32ExitCode = NO_ERROR; dwServiceSpecificExitCode = 0; dwCheckPoint = 0; dwWaitHint = 2000; }
void WINAPI CSystemService::ServiceMain(DWORD argc,LPTSTR *argv) { mainThreadid=::GetCurrentThreadId(); hServiceStatus = RegisterServiceCtrlHandlerEx(ServiceTable[0].lpServiceName,ServiceControl,nullptr); /*if(!hServiceStatus ||!UpdateServiceStatus(SERVICE_START_PENDING,NO_ERROR,0,1,5*60*1000)) { return; } if(ServiceStart && !ServiceStart()) { UpdateServiceStatus(SERVICE_STOPPED,NO_ERROR,0,0,0); return; }*/ if(!UpdateServiceStatus(SERVICE_RUNNING,NO_ERROR,0,0,0)) { return; } if(ServiceStart && !ServiceStart()) { UpdateServiceStatus(SERVICE_STOPPED,1,0,0,0); return; } BOOL bRet; MSG msg; while(true) { bRet = PeekMessage( &msg, 0, 0, 0, PM_REMOVE ); if(bRet==FALSE) { if(ServiceIdle) ServiceIdle(); bRet = GetMessage( &msg, 0, 0, 0 ); if(bRet==0)break; } else { if(msg.message==WM_QUIT) break; } if (bRet == -1) { return; } else { TranslateMessage(&msg); DispatchMessage(&msg); if(ServiceMSG) ServiceMSG(msg); } } UpdateServiceStatus(SERVICE_STOP_PENDING,NO_ERROR,0,1,3000); if(ServiceStop && !ServiceStop()) return; UpdateServiceStatus(SERVICE_STOPPED,NO_ERROR,0,0,0); }
void service_main(u_int argc, char **argv) { SERVICE_STATUS status; SERVICE_STATUS_HANDLE service; /* thread spawned by SCM */ service = RegisterServiceCtrlHandlerEx("nginx", service_handler, ctx); if (service == INVALID_HANDLE_VALUE) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "RegisterServiceCtrlHandlerEx() failed"); return; } status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwCurrentState = SERVICE_START_PENDING; status.dwControlsAccepted = SERVICE_ACCEPT_STOP |SERVICE_ACCEPT_PARAMCHANGE; status.dwWin32ExitCode = NO_ERROR; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 1; status.dwWaitHint = 2000; /* SetServiceStatus() should be called within 80 seconds */ if (SetServiceStatus(service, &status) == 0) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "SetServiceStatus() failed"); return; } /* init */ status.dwCurrentState = SERVICE_RUNNING; status.dwCheckPoint = 0; status.dwWaitHint = 0; if (SetServiceStatus(service, &status) == 0) { ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "SetServiceStatus() failed"); return; } /* call master or worker loop */ /* * master should use event notification and look status * single should use iocp to get notifications from service handler */ }
// Service Main Function // When the service control manager receives a request to start a service, it // starts the service process (if it is not already running). The main thread // of the service process calls the StartServiceCtrlDispatcher function with // a pointer to an array of SERVICE_TABLE_ENTRY structures. Then the service // control manager sends a start request to the service control dispatcher for // this service process. The service control dispatcher creates a new thread // to execute the ServiceMain function of the service being started. VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { TRACE(">ServiceMain PID=%d TID=%d \r\n", GetCurrentProcessId(), GetCurrentThreadId()); // Register a control handler function that will be invoked when the control // dispatcher receives control requests for this service. g_hServiceStatus = RegisterServiceCtrlHandlerEx(SERVICE_NAME, ServiceCtrlHandler, NULL); if(g_hServiceStatus == 0) { DWORD dwError = GetLastError(); TRACE(L"StartServiceCtrlDispatcher Error: %04x \r\n",dwError); return; } // Initialize service status and report SERVICE_START_PENDING to the SCM g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING; g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwWin32ExitCode = NO_ERROR; g_ServiceStatus.dwServiceSpecificExitCode = 0; g_ServiceStatus.dwCheckPoint = 1; g_ServiceStatus.dwWaitHint = 10000; SetServiceStatus(g_hServiceStatus,&g_ServiceStatus); // Service initialization logic would go here for(int i=0; i<9; i++) { TRACE("Initializing Service: %d \r\n",i); Sleep(1000); g_ServiceStatus.dwCheckPoint++; SetServiceStatus(g_hServiceStatus,&g_ServiceStatus); } // Report SERVICE_RUNNING to the SCM g_ServiceStatus.dwControlsAccepted = (SERVICE_CONTROL_INTERROGATE | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; g_ServiceStatus.dwCheckPoint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); // Main service logic would go here do { TRACE("Service Running \r\n"); } while(WaitForSingleObject(g_hServiceStopEvent,1000) != WAIT_OBJECT_0); // Report SERVICE_STOPPED to the SCM g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwCheckPoint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); TRACE("<ServiceMain \r\n"); }
/* Service initialisation */ void WINAPI service_main(unsigned long argc, char **argv) { if (_snprintf(service_name, sizeof(service_name), "%s", argv[0]) < 0) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "service_name", "service_main()", 0); return; } /* Initialise status */ ZeroMemory(&service_status, sizeof(service_status)); service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; service_status.dwWin32ExitCode = NO_ERROR; service_status.dwServiceSpecificExitCode = 0; service_status.dwCheckPoint = 0; service_status.dwWaitHint = NSSM_WAITHINT_MARGIN; /* Signal we AREN'T running the server */ process_handle = 0; pid = 0; /* Register control handler */ service_handle = RegisterServiceCtrlHandlerEx(NSSM, service_control_handler, 0); if (! service_handle) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_REGISTERSERVICECTRLHANDER_FAILED, error_string(GetLastError()), 0); return; } log_service_control(service_name, 0, true); service_status.dwCurrentState = SERVICE_START_PENDING; service_status.dwWaitHint = throttle_delay + NSSM_WAITHINT_MARGIN; SetServiceStatus(service_handle, &service_status); if (is_admin) { /* Try to create the exit action parameters; we don't care if it fails */ create_exit_action(argv[0], exit_action_strings[0]); set_service_recovery(0, service_name); } /* Used for signalling a resume if the service pauses when throttled. */ throttle_timer = CreateWaitableTimer(0, 1, 0); if (! throttle_timer) { log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_CREATEWAITABLETIMER_FAILED, service_name, error_string(GetLastError()), 0); } monitor_service(); }
// // Purpose: // Entry point for the service // // Parameters: // dwArgc - Number of arguments in the lpszArgv array // lpszArgv - Array of strings. The first string is the name of // the service and subsequent strings are passed by the process // that called the StartService function to start the service. // // Return value: // None. // VOID WINAPI CService::Main( DWORD dwArgc, LPTSTR * lpszArgv ) { HANDLE hDataMgr = NULL; HANDLE hRpcServer = NULL; CHAR DbPath[MAX_PATH] = {0}; printfEx(MOD_SERVICE, PRINTF_LEVEL_INFORMATION, "begin"); __try { // Register the handler function for the service CService::GetInstance()->m_SvcStatusHandle = RegisterServiceCtrlHandlerEx(CService::GetInstance()->m_tchServiceName, CtrlHandler, NULL); if (!CService::GetInstance()->m_SvcStatusHandle ) { printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "RegisterServiceCtrlHandler failed. (%d)", GetLastError()); __leave; } // These SERVICE_STATUS members remain as set here CService::GetInstance()->m_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; CService::GetInstance()->m_SvcStatus.dwServiceSpecificExitCode = 0; // Report initial status to the SCM CService::GetInstance()->ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000); // Perform service-specific initialization and work. if (!CService::GetInstance()->Init(dwArgc, lpszArgv)) { printfEx(MOD_SERVICE, PRINTF_LEVEL_ERROR, "Init failed"); __leave; } } __finally { ; } printfEx(MOD_SERVICE, PRINTF_LEVEL_INFORMATION, "end"); return ; }
void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv) { g_hStatusHandle = RegisterServiceCtrlHandlerEx( SERVICE_NAME, (LPHANDLER_FUNCTION_EX)service_ctrl, NULL); if (g_hStatusHandle == NULL){ goto cleanup; } SendStatusScm(SERVICE_START_PENDING, 0, 1); SendStatusScm(SERVICE_RUNNING, 0, 0); StartMain(TRUE); cleanup: SendStatusScm(SERVICE_STOPPED, 0, 0); return; }
static void WINAPI service_main(DWORD argc, LPTSTR* argv) { /* initialise service status */ serviceStatus.dwServiceType=SERVICE_WIN32; serviceStatus.dwCurrentState=SERVICE_STOPPED; serviceStatus.dwControlsAccepted=0; serviceStatus.dwWin32ExitCode=NO_ERROR; serviceStatus.dwServiceSpecificExitCode=NO_ERROR; serviceStatus.dwCheckPoint=0; serviceStatus.dwWaitHint=0; serviceStatusHandle= RegisterServiceCtrlHandlerEx(service_name, control_handler,0); if(serviceStatusHandle) { /* service is starting */ serviceStatus.dwCurrentState=SERVICE_START_PENDING; SetServiceStatus(serviceStatusHandle, &serviceStatus); /* do initialisation here */ stopServiceEvent=CreateEvent(0, FALSE, FALSE, 0); /* running */ serviceStatus.dwControlsAccepted|= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE); serviceStatus.dwCurrentState=SERVICE_RUNNING; SetServiceStatus(serviceStatusHandle, &serviceStatus); monitor_sessions(); /* service was stopped */ serviceStatus.dwCurrentState=SERVICE_STOP_PENDING; SetServiceStatus(serviceStatusHandle, &serviceStatus); /* do cleanup here */ CloseHandle(stopServiceEvent); stopServiceEvent=0; /* service is now stopped */ serviceStatus.dwControlsAccepted&= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); serviceStatus.dwCurrentState=SERVICE_STOPPED; SetServiceStatus(serviceStatusHandle, &serviceStatus); } }
void CServiceRunner::Run() { // Register the control handler. m_serviceHandler = RegisterServiceCtrlHandlerEx(m_parameters.serviceName.c_str(), globalControlHandler, this); if (!m_serviceHandler) { CEventLogger::Get().Log(EVENTLOG_ERROR_TYPE, WEBINOS_SERVER_EVENT_REGISTERSERVICECTRLHANDER_FAILED, CEventLogger::Get().LookupError(GetLastError()), 0); } else { // Initialise service status. ZeroMemory(&m_status, sizeof(m_status)); m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; m_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; m_status.dwWin32ExitCode = NO_ERROR; m_status.dwServiceSpecificExitCode = 0; m_status.dwCheckPoint = 0; m_status.dwWaitHint = 3000; m_status.dwCurrentState = SERVICE_START_PENDING; m_status.dwWaitHint = 3000; SetServiceStatus(m_serviceHandler, &m_status); } // Create a timer used to wait before restarting node process. m_restartTimer = CreateWaitableTimer(0, 1, 0); if (!m_restartTimer) { CEventLogger::Get().Log(EVENTLOG_WARNING_TYPE, WEBINOS_SERVER_EVENT_CREATEWAITABLETIMER_FAILED, m_parameters.serviceName.c_str(), CEventLogger::Get().LookupError(GetLastError()), 0); } if (m_serviceHandler) { // Update service status. m_status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(m_serviceHandler, &m_status); } Start(); DWORD monitorThreadId; m_monitorThreadHandle = CreateThread(NULL, 0, MonitorThread, this, 0, &monitorThreadId); }
static void WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) { /* register the handler function for the service */ statusHandle = RegisterServiceCtrlHandlerEx(SVCNAME, SvcCtrlHandler, NULL); if (!statusHandle) { SvcReportEvent(TEXT("RegisterServiceCtrlHandler")); return; } status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwServiceSpecificExitCode = 0; /* report initial status to the SCM */ report_status(SERVICE_START_PENDING, NO_ERROR, 3000); /* report service-specific initialization and work */ SvcInit(dwArgc, lpszArgv); }
static void WINAPI service_main(G_GNUC_UNUSED DWORD argc, G_GNUC_UNUSED CHAR *argv[]) { DWORD error_code; gchar* error_message; service_handle = RegisterServiceCtrlHandlerEx(service_name, service_dispatcher, NULL); if (service_handle == 0) { error_code = GetLastError(); error_message = g_win32_error_message(error_code); MPD_ERROR("RegisterServiceCtrlHandlerEx() failed: %s", error_message); } service_notify_status(SERVICE_START_PENDING); mpd_main(service_argc, service_argv); service_notify_status(SERVICE_STOPPED); }
HRESULT ChangeYontmaServiceStatus(DWORD dwServiceStatus, LPVOID lpContext) { SERVICE_STATUS status; SERVICE_STATUS_HANDLE hSrv; hSrv = RegisterServiceCtrlHandlerEx(SERVICE_NAME, (LPHANDLER_FUNCTION_EX)ServiceHandlerEx, lpContext); status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwCurrentState = dwServiceStatus; status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE | SERVICE_ACCEPT_POWEREVENT; status.dwWin32ExitCode = 0; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 0; status.dwWaitHint = 3000; if(!SetServiceStatus(hSrv, &status)) { return HRESULT_FROM_WIN32(GetLastError()); } return S_OK; }
static VOID WINAPI RunAsServiceMain( _In_ DWORD dwArgc, _In_ LPTSTR *lpszArgv ) { PPH_STRING portName; UNICODE_STRING portNameUs; LARGE_INTEGER timeout; memset(&RunAsServiceStop, 0, sizeof(PHSVC_STOP)); RunAsServiceStatusHandle = RegisterServiceCtrlHandlerEx(RunAsServiceName->Buffer, RunAsServiceHandlerEx, NULL); SetRunAsServiceStatus(SERVICE_RUNNING); portName = PhConcatStrings2(L"\\BaseNamedObjects\\", RunAsServiceName->Buffer); PhStringRefToUnicodeString(&portName->sr, &portNameUs); // Use a shorter timeout value to reduce the time spent running as SYSTEM. timeout.QuadPart = -5 * PH_TIMEOUT_SEC; PhSvcMain(&portNameUs, &timeout, &RunAsServiceStop); SetRunAsServiceStatus(SERVICE_STOPPED); }
void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv) { g_hStatusHandle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, service_ctrl, NULL); if( g_hStatusHandle != NULL ){ ReportServiceStatus(SERVICE_START_PENDING, 0, 1, 10000); //メインスレッドに対するCOMの初期化 CoInitialize(NULL); //ここでは単純な(時間のかからない)初期化のみ行う g_pMain = new CEpgTimerSrvMain; ReportServiceStatus(SERVICE_RUNNING, SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT, 0, 0); if( g_pMain->Main(true) == false ){ OutputDebugString(_T("service_main(): Failed to start\r\n")); } delete g_pMain; g_pMain = NULL; CoUninitialize(); ReportServiceStatus(SERVICE_STOPPED, 0, 0, 0); } }
BOOL DFServiceStatus::Initialize(PCTSTR szServiceName, LPHANDLER_FUNCTION_EX pFnHandler, PVOID pvContext, BOOL bOwnProcess, BOOL bInteractWithDesktop) { m_hServiceStatus = RegisterServiceCtrlHandlerEx(szServiceName, pFnHandler, pvContext); DFASSERT(m_hServiceStatus != NULL); dwServiceType = bOwnProcess ? SERVICE_WIN32_OWN_PROCESS : SERVICE_WIN32_SHARE_PROCESS; if(bInteractWithDesktop) { dwServiceType |= SERVICE_INTERACTIVE_PROCESS; } dwCurrentState = SERVICE_START_PENDING; dwControlsAccepted = 0; dwWin32ExitCode = NO_ERROR; dwServiceSpecificExitCode = 0; dwCheckPoint = 0; dwWaitHint = 2000; return (m_hServiceStatus != NULL); }
void Service::_ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv) { m_dbgMsg(L"Entering Service::ServiceMain()"); // Register the control request handler m_Status.dwCurrentState = SERVICE_START_PENDING; #ifndef HANDLEREX m_hServiceStatus = RegisterServiceCtrlHandler(m_szServiceName, Handler); #else HANDLEREX m_hServiceStatus = RegisterServiceCtrlHandlerEx(m_szServiceName, HandlerEx, NULL); #endif HANDLEREX if (m_hServiceStatus == NULL) { m_dbgMsg(L"Service::ServiceMain() Service Not Registered"); EVLOG_ERROR(EVMSG_CTRLHANDLERNOTINSTALLED); return; } m_dbgMsg(L"Service::ServiceMain() Service Registered"); // Start the initialisation if (Initialize()) { // Do the real work. // When the Run function returns, the service has stopped. m_bIsRunning = TRUE; m_Status.dwWin32ExitCode = 0; m_Status.dwCheckPoint = 0; m_Status.dwWaitHint = 0; Run(); } // Tell the service manager we are stopped SetStatus(SERVICE_STOPPED); m_dbgMsg(L"Leaving Service::ServiceMain()"); }
VOID WINAPI ServiceStartAutomatic(DWORD dwArgc, LPTSTR *lpszArgv) { DWORD error = NO_ERROR; settings_t settings; service = RegisterServiceCtrlHandlerEx(automatic_service.name, ServiceCtrlAutomatic, &status); if (!service) { return; } status.dwServiceType = SERVICE_WIN32_SHARE_PROCESS; status.dwCurrentState = SERVICE_START_PENDING; status.dwServiceSpecificExitCode = NO_ERROR; status.dwWin32ExitCode = NO_ERROR; status.dwWaitHint = 3000; if (!ReportStatusToSCMgr(service, &status)) { MsgToEventLog(M_ERR, TEXT("ReportStatusToSCMgr #1 failed")); goto finish; } /* * Create our exit event */ exit_event = create_event(EXIT_EVENT_NAME, false, false, true); if (!exit_event) { MsgToEventLog(M_ERR, TEXT("CreateEvent failed")); goto finish; } /* * If exit event is already signaled, it means we were not * shut down properly. */ if (WaitForSingleObject(exit_event, 0) != WAIT_TIMEOUT) { MsgToEventLog(M_ERR, TEXT("Exit event is already signaled -- we were not shut down properly")); goto finish; } if (!ReportStatusToSCMgr(service, &status)) { MsgToEventLog(M_ERR, TEXT("ReportStatusToSCMgr #2 failed")); goto finish; } /* * Read info from registry in key HKLM\SOFTWARE\OpenVPN */ error = GetOpenvpnSettings(&settings); if (error != ERROR_SUCCESS) { goto finish; } /* * Instantiate an OpenVPN process for each configuration * file found. */ { WIN32_FIND_DATA find_obj; HANDLE find_handle; BOOL more_files; TCHAR find_string[MAX_PATH]; openvpn_sntprintf(find_string, MAX_PATH, TEXT("%s\\*"), settings.config_dir); find_handle = FindFirstFile(find_string, &find_obj); if (find_handle == INVALID_HANDLE_VALUE) { MsgToEventLog(M_ERR, TEXT("Cannot get configuration file list using: %s"), find_string); goto finish; } /* * Loop over each config file */ do { HANDLE log_handle = NULL; STARTUPINFO start_info; PROCESS_INFORMATION proc_info; struct security_attributes sa; TCHAR log_file[MAX_PATH]; TCHAR log_path[MAX_PATH]; TCHAR command_line[256]; CLEAR(start_info); CLEAR(proc_info); CLEAR(sa); if (!ReportStatusToSCMgr(service, &status)) { MsgToEventLog(M_ERR, TEXT("ReportStatusToSCMgr #3 failed")); FindClose(find_handle); goto finish; } /* does file have the correct type and extension? */ if (match(&find_obj, settings.ext_string)) { /* get log file pathname */ if (!modext(log_file, _countof(log_file), find_obj.cFileName, TEXT("log"))) { MsgToEventLog(M_ERR, TEXT("Cannot construct logfile name based on: %s"), find_obj.cFileName); FindClose(find_handle); goto finish; } openvpn_sntprintf(log_path, _countof(log_path), TEXT("%s\\%s"), settings.log_dir, log_file); /* construct command line */ openvpn_sntprintf(command_line, _countof(command_line), TEXT(PACKAGE " --service %s 1 --config \"%s\""), EXIT_EVENT_NAME, find_obj.cFileName); /* Make security attributes struct for logfile handle so it can * be inherited. */ if (!init_security_attributes_allow_all(&sa)) { error = MsgToEventLog(M_SYSERR, TEXT("InitializeSecurityDescriptor start_" PACKAGE " failed")); goto finish; } /* open logfile as stdout/stderr for soon-to-be-spawned subprocess */ log_handle = CreateFile(log_path, GENERIC_WRITE, FILE_SHARE_READ, &sa.sa, settings.append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (log_handle == INVALID_HANDLE_VALUE) { error = MsgToEventLog(M_SYSERR, TEXT("Cannot open logfile: %s"), log_path); FindClose(find_handle); goto finish; } /* append to logfile? */ if (settings.append) { if (SetFilePointer(log_handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER) { error = MsgToEventLog(M_SYSERR, TEXT("Cannot seek to end of logfile: %s"), log_path); FindClose(find_handle); goto finish; } } /* fill in STARTUPINFO struct */ GetStartupInfo(&start_info); start_info.cb = sizeof(start_info); start_info.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; start_info.wShowWindow = SW_HIDE; start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE); start_info.hStdOutput = start_info.hStdError = log_handle; /* create an OpenVPN process for one config file */ if (!CreateProcess(settings.exe_path, command_line, NULL, NULL, TRUE, settings.priority | CREATE_NEW_CONSOLE, NULL, settings.config_dir, &start_info, &proc_info)) { error = MsgToEventLog(M_SYSERR, TEXT("CreateProcess failed, exe='%s' cmdline='%s' dir='%s'"), settings.exe_path, command_line, settings.config_dir); FindClose(find_handle); CloseHandle(log_handle); goto finish; } /* close unneeded handles */ Sleep(1000); /* try to prevent race if we close logfile * handle before child process DUPs it */ if (!CloseHandle(proc_info.hProcess) || !CloseHandle(proc_info.hThread) || !CloseHandle(log_handle)) { error = MsgToEventLog(M_SYSERR, TEXT("CloseHandle failed")); goto finish; } } /* more files to process? */ more_files = FindNextFile(find_handle, &find_obj); } while (more_files); FindClose(find_handle); } /* we are now fully started */ status.dwCurrentState = SERVICE_RUNNING; status.dwWaitHint = 0; if (!ReportStatusToSCMgr(service, &status)) { MsgToEventLog(M_ERR, TEXT("ReportStatusToSCMgr SERVICE_RUNNING failed")); goto finish; } /* wait for our shutdown signal */ if (WaitForSingleObject(exit_event, INFINITE) != WAIT_OBJECT_0) { MsgToEventLog(M_ERR, TEXT("wait for shutdown signal failed")); } finish: if (exit_event) { CloseHandle(exit_event); } status.dwCurrentState = SERVICE_STOPPED; status.dwWin32ExitCode = error; ReportStatusToSCMgr(service, &status); }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------ VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv){ sprintf( msg_err, "ServiceMain - init." ); DWORD xParam = 1; JOB = 1; // -- hServiceStatus = RegisterServiceCtrlHandlerEx( service_name, (LPHANDLER_FUNCTION_EX)ServiceCtrlHandlerEx, (PVOID)&xParam ); if( !hServiceStatus ){ prn_err( "RegisterServiceCtrlHandlerEx failed.", GetLastError() ); return; } // init service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; service_status.dwCurrentState = SERVICE_START_PENDING; service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE; service_status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; service_status.dwServiceSpecificExitCode = 0; service_status.dwCheckPoint = 0; service_status.dwWaitHint = 5000; if( !SetServiceStatus( hServiceStatus, &service_status )){ prn_err( "SetServiceStatus 'NULL' failed.", GetLastError() ); return; } // Rabota service_status.dwCurrentState = SERVICE_RUNNING; service_status.dwWin32ExitCode = NO_ERROR; // Set New if( !SetServiceStatus( hServiceStatus, &service_status )){ prn_err( "SetServiceStatus 'SERVICE_START_PENDING' failed.", GetLastError() ); return; } // -- usleep(10000); // ------------------------------------------------------------------------ prn_log( "." ); SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ); prn_log( "START SERVICE." ); // --------------------------------- if( !init_conf( service_work, service_name, &conf )){ // возврат всегда "1" prn_err( "Init config-data failed. This message can not be", 0 ); }else{ if( strcasecmp( conf.log_debug, "Off" ) == 0 ) DEBUG = 0; else prn_log( "Logger - DEBUG" ); // -- if( strcasecmp( conf.user_proc, "0" ) == 0 ) prn_log( "WARNING! User Process - disabled." ); if( strcasecmp( conf.maintenance, "0" ) == 0 ) prn_log( "WARNING! Maintenances - disabled." ); if( strcasecmp( conf.git_exec, "0" ) == 0 ) prn_log( "WARNING! Git status - disabled." ); } // -- JOB = 2; // Создаем поток логирования cygwin (сокет /dev/log) для ssh-сессий HANDLE hCygWinLogThread = CreateThread( NULL, 0, &CygWinLogThread, (LPVOID)&conf, 0, NULL ); if( !hCygWinLogThread ){ prn_err( "LogSocket: Create CygWinLogThread - failed.", GetLastError() ); } // --------------------------------- JOB = 3; if( !open_send( conf.zbx_server, conf.zbx_port, conf.zbx_host )){ prn_log( "WARNING! Sender not available: Maintenances - will not be available." ); strcpy( conf.maintenance, "0" ); } // --------------------------------- JOB = 22; // потоки обслуживания // HANDLE hGTimeThread = CreateThread( NULL, 0, >imeThread, NULL, 0, NULL );// поток // --------------------------------- usleep(10000); JOB = 101; send_sm_string( "SM;SyMon;START;!" ); // -- // проверка активных сессий DWORD pCount; HANDLE hToken; PWTS_SESSION_INFO ppSessionInfo = NULL; HANDLE hTS = WTSOpenServer( "" ); // -- if( WTSEnumerateSessions(hTS, 0, 1, &ppSessionInfo, &pCount )){ while( pCount ){ if( ppSessionInfo->State == 0 ){ if( WTSQueryUserToken( ppSessionInfo->SessionId, &hToken )) entering_info( ppSessionInfo->SessionId, 5, hToken, NULL ); else prn_err( "WTS Token failed.", GetLastError() ); } ppSessionInfo++; pCount--; } } // ----------------------------------- while( JOB > 100 ){ // главный цикл git_test(); // выполнение отложенных (тормозных) функций sleep(1); } // -- // CloseHandle( hGTimeThread ); sleep( 2 ); close_send(); sprintf( msg_err, "ServiceMain - return." ); // ------------------------------------------------------------------------ }