// service_test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#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 成功。此时进入服务管理手动开启服务