編寫Windows服務應該注意的一些心得

心得一 :核心對象的引用計數

        Windows系統中核心對象,比如窗口句柄,文件句柄,Event等等,在Windows的內部管理機制中全部採用引用計數方式管理,比如hService = CreateService(..),經過這次調用,系統中hService這個對象的的引用計數加1,而創建後如果不關閉再次通過OpenSCManager和OpenService打開的猶豫上次的服務句柄沒有關閉,再次從服務配置管理數據庫中取出的該Service的句柄將發生變化,雖然可以被DeleteServcie刪除,但刪除後,在控制面板中查詢到,當前狀態爲“已禁用”。必須等待控制工具退出後,該服務才從控制面板的“服務”中消失。至於具體原因,目前未知,也未相通,但覺得和CreateService後沒有關閉句柄的引用有關。

心得二 :關於StartServiceCtrlDispatcher

       它的原始定義:BOOL StartServiceCtrlDispatcher( const LPSERVICE_TABLE_ENTRY lpServiceTable);請參看關於lpServiceTable的原始定義:

lpServiceTable [in] Pointer to an array of SERVICE_TABLE_ENTRY structures containing one entry for each service that can execute in the calling process. The members of the last entry in the table must have NULL values to designate the end of the table.

這個參數指明的是一組指向SERVICE_TABLE_ENTRY的結構,一組意味着不可以如下傳遞

SERVICE_TABLE_ENTRY  ste;
StartServiceCtrlDispatcher(&ste);

這樣傳遞如果運氣好,也許會服務加載成功,但如果運氣不好,就會有“等待 Win32 Service that help Vise administrtor to control its functions 服務的連接超時(30000 毫秒)。”“由於下列錯誤,Win32 Service that help Vise administrtor to control its functions 服務啓動失敗:服務沒有及時響應啓動或控制請求。 ”等問題出現,可能還會出現有如上面心得中出現的“已禁用”。因爲“Pointer to an array ”“The members of the last entry in the table must have NULL values to designate the end of the table.”兩句指明,數組的最後一個這個結構,必須以NULL結尾。至於內部實現雖然不知道,但如果出現連續非NULL,可能就會出現上面的情形了。

發佈了29 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章