2008-12-05 101 views
0

我使用VS6和ATL與CServiceModule來實現自定義Windows服務。如果發生致命錯誤,服務應該自行關閉。由於CServiceModule是通過_Module變量可以在所有的文件,我認爲是這樣造成CServiceModule ::運行停止抽水信息和自行關閉Windows服務關閉

PostThreadMessage(_Module.dwThreadID, WM_QUIT, 0, 0); 

這是正確的,或者你有更好的主意嗎?

回答

0

對於自我關機,您將命令發送到服務管理器。試試這個樣本:


BOOL StopServiceCmd (const char * szServiceName) 
{ 
    SC_HANDLE schService; 
    SC_HANDLE schSCManager; 
    SERVICE_STATUS ssStatus;  // current status of the service 
    BOOL bRet; 
    int iCont=0; 

    schSCManager = OpenSCManager( 
     NULL, // machine (NULL == local) 
     NULL, // database (NULL == default) 
     SC_MANAGER_ALL_ACCESS // access required 
     ); 
    if (schSCManager) 
    { 
     schService = OpenService(schSCManager, szServiceName, SERVICE_ALL_ACCESS); 

     if (schService) 
     { 
      // try to stop the service 
      if (ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus)) 
      { 
       Sleep(1000); 

       while(QueryServiceStatus(schService, &ssStatus)) 
       { 
        iCont++; 
        if (ssStatus.dwCurrentState == SERVICE_STOP_PENDING) 
        { 
         Sleep(1000); 
         if (iCont > 4) break; 
        } 
        else 
         break; 
       } 

       if (ssStatus.dwCurrentState == SERVICE_STOPPED) 
        bRet = TRUE; 
       else 
        bRet = FALSE; 
      } 

      CloseServiceHandle(schService); 
     } 
     else 
      bRet = FALSE; 

     CloseServiceHandle(schSCManager); 
    } 
    else 
     bRet = FALSE; 

    return bRet; 
} 
0

我相信,如果你這樣做,那麼服務經理會認爲你的服務已經崩潰,如果用戶將它設置爲自動重啓,它會。

在.NET中,您使用ServiceController來指示服務關閉。我期望它在Win32中類似,因爲.NET中的大部分東西都只是包裝器。對不起,我沒有方便關閉服務的C++代碼,但這裏是.NET代碼。這將有希望幫助您Google所需的信息,或者在MSDN中查找文檔。

這是來自一些測試套件代碼,因此錯誤檢查的樣式;)您將需要將此代碼放入一個線程中,以便處理關閉消息。

private void stopPLService(bool close) 
    { 
    if (m_serviceController == null) 
    { 
     m_serviceController = new ServiceController("PLService"); 
    } 

    WriteLine("StopPLService"); 

    if (m_serviceController != null) 
    { 
     try 
     { 
      m_serviceController.Stop(); 
     } 
     catch 
     { 
      // Probably just means that it wasn't running or installed, ignore 
     } 

     // Wait up to 30 seconds for the service to stop 
     try 
     { 
      m_serviceController.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); 
     } 
     catch (System.ServiceProcess.TimeoutException) 
     { 
      Assert.Fail("Timeout waiting for PLService to stop"); 
     } 
     catch 
     { 
      // Not installed, we only care in the start 
     } 
     if (close) 
     { 
      m_serviceController.Close(); 
      m_serviceController = null; 
     } 
    } 
    } 
0

您可能想要使用ControlService或ControlServiceEx方法關閉您的服務。您應該能夠從CServiceModule獲取所需的句柄。