程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C語言實現Windows服務並進行安裝部署

C語言實現Windows服務並進行安裝部署

編輯:關於C語言

C語言實現Windows服務並進行安裝部署


// service_test.cpp : 定義控制台應用程序的入口點。
//


#include "stdafx.h"
#include
#include


#define SLEEP_TIME 5000
#define LOGFILE "D:\\TEST\\memstatuse.txt"


int WriteToLog(char *);


SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStaus;


void ServiceMain(int argc,char **argv);
void ControlHandler(DWORD request);
int InitService();




int _tmain(int argc, _TCHAR* argv[])
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = L"MemoryStatus";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;


ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;


StartServiceCtrlDispatcher(ServiceTable);



return 0;
}
void ServiceMain(int argc,char **argv)
{
BOOL bRet;
bRet = TRUE;


ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN;


ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;


hStaus = RegisterServiceCtrlHandler(L"MemoryStatus",(LPHANDLER_FUNCTION)ControlHandler);
if (hStaus == (SERVICE_STATUS_HANDLE)0)
{
return;
}


ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hStaus,&ServiceStatus);


char memory[256];


while(ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
GetCurrentDirectory(256,(LPWSTR)memory);
int result = WriteToLog(memory);


if (result)
{
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStaus,&ServiceStatus);
return;
}
Sleep(SLEEP_TIME);





}
return;
}


void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
WriteToLog("Monitoring stopped");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hStaus,&ServiceStatus);
return;

case SERVICE_CONTROL_SHUTDOWN:
WriteToLog("Monitoring stopped");
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hStaus,&ServiceStatus);
return;


default:
break;



}
SetServiceStatus(hStaus,&ServiceStatus);
return;
}


//輸出到日志文件
int WriteToLog(char * str)
{
FILE *log;
log = fopen(LOGFILE,"a+");
if (log==NULL)
{
return -1;
}
fprintf(log,"%s\n",str);
fclose(log);
return 0;

}



程序運行生成service_test.exe ,用管理員身份進入到控制台,cd C:\Windows\system32 然後利用sc.exe工具 sc create service_test binPath= D:\TEST\service_test.exe控制台中會打印出 CreateService 成功。此時進入服務管理手動開啟服務


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved