我的服务不会停止

时间:2011-10-04 15:31:34

标签: c++ winapi

每当我尝试通过服务管理器停止服务时,都会收到以下错误,服务仍处于启动状态。 “无法停止本地计算机上的服务。该服务未返回错误。这可能是内部Windows错误或内部服务错误。” 我在这个问题上遇到了麻烦,我试图尽可能地遵循微软的逻辑。 http://msdn.microsoft.com/en-us/library/windows/desktop/bb540474(v=vs.85).aspx 在.Net 1.1中存在类似的问题,如果你搜索,你会发现;但是,我根本没有使用framweork。

void WINAPI serviceCtrlHandler(DWORD dwCtrl )
{

    switch(dwCtrl)
    {
        case SERVICE_CONTROL_STOP:
            ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
            SetEvent(stopEvent); 
            ReportSvcStatus(serviceStatus->dwCurrentState, NO_ERROR, 0);

            return;
        case SERVICE_CONTROL_INTERROGATE:
            break;
        default:
            break;
    }
}

void WINAPI startMain(DWORD argc, LPTSTR *argv)
{
    serviceStatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, serviceCtrlHandler);

    serviceStatus->dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    serviceStatus->dwServiceSpecificExitCode = NO_ERROR;

    if (serviceStatusHandle == 0)
    {
        debug->DebugMessage(L"RegisterServiceCtrlHandler() failed, error: " + Error::GetErrorMessageW(GetLastError()));
        return;
    }

    ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);

    if (!SetServiceStatus(serviceStatusHandle, serviceStatus))
    {
        //debug->DebugMessage(L"SetserviceStatus() failed, error: " + Error::GetErrorMessageW(GetLastError()));
        //return;
    }

    stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);

    boost::thread dust_main_thread(dust_main);

    while(1)
    {
        WaitForSingleObject(stopEvent, INFINITE);

        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
        return;
    }

}

VOID ReportSvcStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint)
{
    static DWORD dwCheckPoint = 1;

    serviceStatus->dwCurrentState = dwCurrentState;
    serviceStatus->dwWin32ExitCode = dwWin32ExitCode;
    serviceStatus->dwWaitHint = dwWaitHint;

    if (dwCurrentState == SERVICE_START_PENDING)
        serviceStatus->dwControlsAccepted = 0;
    else serviceStatus->dwControlsAccepted = SERVICE_ACCEPT_STOP;

    if ((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED))
        serviceStatus->dwCheckPoint = 0;
    else 
        serviceStatus->dwCheckPoint = dwCheckPoint++;

    SetServiceStatus(serviceStatusHandle, serviceStatus);
}

1 个答案:

答案 0 :(得分:0)

运行该服务,然后将调试器附加到正在运行的进程。在serviceCtrlHandler和WaitForSingleObject(stopEvent,INFINITE)之后放置一个断点 - 确保你认为应该发生的事情。