HRESULT Service_Monitor::MonitoringService()

in src/ServiceMonitor/ServiceMonitor.cpp [205:252]


HRESULT Service_Monitor::MonitoringService(LPCTSTR pServiceName, DWORD dwStatus, HANDLE hStopEvent)
{
    HRESULT   hr = S_OK;
    DWORD     dwError = ERROR_SUCCESS;
    DWORD     dwWaitResult;
    SC_HANDLE hService;
    SERVICE_NOTIFY sNotify;

    hr = GetServiceHandle(pServiceName, &hService);
    if(FAILED(hr))
    {
        goto Finished;
    }

    sNotify.dwVersion = SERVICE_NOTIFY_STATUS_CHANGE;
    sNotify.pfnNotifyCallback = (PFN_SC_NOTIFY_CALLBACK)NotifyCallBack;
    sNotify.pszServiceNames = (LPWSTR) pServiceName;
    sNotify.pContext = hStopEvent;

    dwError = NotifyServiceStatusChange(hService, dwStatus, &sNotify);
    if (dwError != ERROR_SUCCESS)
    {
        hr = HRESULT_FROM_WIN32(dwError);
        _tprintf(L"\nERROR: fail to register status change callback [%x]\n", hr);
        goto Finished;
    }

    dwWaitResult = WaitForSingleObjectEx(hStopEvent, INFINITE, TRUE);
    switch (dwWaitResult)
    {
        // Event object was signaled
    case WAIT_OBJECT_0:
    case WAIT_IO_COMPLETION:
        break;

        // An error occurred
    default:
        hr = HRESULT_FROM_WIN32(GetLastError());
        _tprintf(L"\nERROR: Monitoring service '%s' wait error [%x]\n", pServiceName, hr);
    }

Finished:
    if (hService != NULL)
    {
        CloseServiceHandle(hService);
    }
    return hr;
}