玩轉Windows服務系列——使用Boost.Application快速構建Windows服務
阿新 • • 發佈:2018-12-30
Boost.Application簡介
Boost.Application 是一個開源的C++庫,主要用於構建跨平臺的服務,包括Windows、Unix、Linux、MaxOS等。沒錯,這個庫可以用來做跨平臺的服務。Boost.Application 使用開源協議 Boost Software License, Version 1.0。
Boost.Application 目前還不是Boost官方的庫,想要使用它,需要到Github上下載最新程式碼,當前版本為0.4.12。
用Boost.Application構建Windows服務
第一步,用VS建立一個控制檯程式。
第二步,配置Boost.Application以及Boost的include路徑和lib路徑。
第三步,將Boost.Application目錄下的README.md檔案中的示例程式碼拷貝到 myservice.cpp 中並覆蓋原來所有的程式碼。
第四部,將編譯選項設定為多位元組
第五步,編譯並執行程式
由於這時候還沒有註冊服務,所以以控制檯的方式執行起來就會報錯了。
第六步,將程式註冊為Windows服務,在命令列中執行如下命令:
sc create myservice binpath= "D:\Code\C++\CommonCode\Win32\Debug\myservice.exe" type= own start= demand displayname= "service test"
在Windows服務管理器中可以看到剛剛建立的服務:
第七步,啟動服務,然後停止服務,在服務所在目錄,可以看到產生了一個log.txt檔案,
Start Log... ----------------------------- ---------- Arg List --------- ----------------------------- myservice ----------------------------- 0, running... 1, running... 2, running... Stoping my application...
這樣,一個完整的Windows服務就算完成了。
註冊服務程式
在Boost.Application 的 “Boost.Application\example\setup”目錄下,有一個用於註冊解除安裝服務的示例程式碼。
將此示例程式碼編譯為service_setup_ex.exe程式後,就可以使用此程式進行服務的註冊和解除安裝了。
安裝服務,支援設定程式路徑、服務名字、顯示名字、描述、啟動模式、依賴服務等,如下:
service_setup_ex.exe -i --name="My Service" --path="c:\myservice\service.exe" service_setup_ex.exe -i --name="My Service" --path="c:\myservice\service.exe" --display="My Service" service_setup_ex.exe -i --name="My Service" --path="c:\myservice\service.exe" --display="My Service" --description "Service Description" service_setup_ex.exe -i --name="My Service" --path="c:\myservice\service.exe" --user=".\Renato Tegon Forti" --pass="x1x1x1" service_setup_ex.exe -i --name="My Service" --path="c:\myservice\service.exe" --start="manaul" --depends="service1\service2\service3"
檢測服務:
service_setup_ex.exe -c --name="My Service"
解除安裝服務:
service_setup_ex.exe -u --name="My Service" --path="c:\myservice\service.exe"