用VC 建立Service服務應用程式

2021-04-15 17:38:10 字數 2396 閱讀 9705

為什麼要使用服務應該程式

//定義全域性函式變數

void init();

bool isinstalled();

bool install();

bool uninstall();

void logevent(lpctstr pszformat, ...);

void winapi servicemain();

void winapi servicestrl(dword dwopcode);

tchar szservicename = _t("servicetest");

bool binstall;

service_status_handle hservicestatus;

service_status status;

dword dwthreadid;

三、新增init初始化函式

這裡主要是設定服務控制代碼和狀態。

hservicestatus = null;

status.dwservicetype = service_win32_own_process;

status.dwcurrentstate = service_stopped;

tatus.dwcontrolsaccepted = service_accept_stop;

status.dwwin32exitcode = 0;

status.dwservicespecificexitcode = 0;

status.dwcheckpoint = 0;

status.dwwaithint = 0;

四、新增安裝和刪除服務函式

這裡主要是用到了五個函式openscmanager、createservice、openservice、controlservice、deleteservice。openscmanager用於開啟服務控制管理器;createservice用於建立服務;openservice用於開啟已有的服務,返回該服務的控制代碼;controlservice則用於控制已開啟的服務狀態,這裡是讓服務停止後才刪除;deleteservice用於刪除指定服務。

bool install();

bool uninstall();

五、新增服務主線程函式和控制函式

這裡呼叫registerservicectrlhandler來註冊服務的控制函式,這裡要設定status.dwcontrolsaccepted為service_accept_stop,否則你不能控制這個服務的狀態。

void winapi servicemain()

setservicestatus(hservicestatus, &status);

status.dwwin32exitcode = s_ok;

status.dwcheckpoint = 0;

status.dwwaithint = 0;

status.dwcurrentstate = service_running;

setservicestatus(hservicestatus, &status);

//模擬服務的執行,10後自動退出。應用時將主要任務放於此即可

int i = 0;

while (i < 10)

//status.dwcurrentstate = service_stopped;

setservicestatus(hservicestatus, &status);

logevent(_t("service stopped"));}

六、在主線程函式裡註冊控制函式和程式

執行主體

void winapi servicemain()…}

七、在main函式裡註冊新增安裝、刪除、註冊主函式

int apientry winmain(hinstance hinstance,

hinstance hprevinstance,

lpstr lpcmdline,

int ncmdshow),};

if (stricmp(lpcmdline, "/install") == 0)

else if (stricmp(lpcmdline, "/uninstall") == 0)

else

}return 0;}

八、總結

其實做乙個服務程式並不難,主要是懂得程式的執行體放於**?註冊程式的主函式和註冊控制函式,如果這兩個沒有註冊的話,你的程式就不知道如何去控制了。status.dwcontrolsaccepted = service_accept_stop;這個也重要,如果你沒有設定的話,那麼服務就不會受你控制了。

用 VC 建立 Windows 服務程式

本文主要介紹了 openscmanager createservice openservice controlservice deleteservice registerservicectrlhandler setservicestatus startservicectrldispatcher等操作...

用 VC 建立 Windows 服務程式

本文主要介紹了 openscmanager createservice openservice controlservice deleteservice registerservicectrlhandler setservicestatus startservicectrldispatcher等操作...

k8s實戰五 用service建立前後端應用

官方建議 後端應用 埠不指定,前端像nginx這種可以指定 cat hello.yaml kind deployment metadata name hello spec selector matchlabels 這麼多label tier backend track stable replicas...