万捷博客

万捷博客
一个知识汇聚的地方
首页 » c++ » C++写windows系统服务示例[源码]

C++写windows系统服务示例[源码]

直接上代码!

#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <tchar.h>


//*注意:程序编译后请用CMD通过以下命令注册、启动、卸载服务,不是直接双击运行
//*注意:生成时请用Release目录,不要用Debug

//CMD命令 注册服务
//sc create testservice binPath = 文件路径

//CMD命令 启动服务
//sc start testservice

//CMD命令 卸载服务
//sc delete testservice



using namespace std;

#define SLEEP_TIME 5000 //任务循环间隔时间,单位:毫秒

#define FILE_PATH "C:\\log.txt" //信息输出文件名

bool brun = false;


SERVICE_STATUS servicestatus;

SERVICE_STATUS_HANDLE hstatus;

int WriteToLog(char* str);

void WINAPI ServiceMain(int argc, char** argv);

void WINAPI CtrlHandler(DWORD request);

int InitService();


//输出日志
int WriteToLog(char* str)
{


	FILE* pfile;
	pfile = fopen(FILE_PATH, "a+");

	if (pfile == NULL)
	{
		return -1;
	}
	fprintf(pfile, "%s\n", str);

	fclose(pfile);
	return 0;
}

void WINAPI ServiceMain(int argc, char** argv)
{
	servicestatus.dwServiceType = SERVICE_WIN32;
	servicestatus.dwCurrentState = SERVICE_START_PENDING;
	servicestatus.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP;//在本例中只接受系统关机和停止服务两种控制命令
	servicestatus.dwWin32ExitCode = 0;
	servicestatus.dwServiceSpecificExitCode = 0;
	servicestatus.dwCheckPoint = 0;
	servicestatus.dwWaitHint = 0;

	hstatus = ::RegisterServiceCtrlHandler("testservice", CtrlHandler);

	if (hstatus == 0)

	{

		WriteToLog("注册服务Ctrl处理程序失败");
		return;

	}

	WriteToLog("注册服务Ctrl处理程序成功");

	//向SCM 报告运行状态

	servicestatus.dwCurrentState = SERVICE_RUNNING;

	SetServiceStatus(hstatus, &servicestatus);

	//下面就开始任务循环了,你可以添加你自己希望服务做的工作

	brun = true;

	MEMORYSTATUS memstatus;

	char str[100];

	memset(str, '\0', 100);


	while (brun)
	{
		GlobalMemoryStatus(&memstatus);
		int availmb = memstatus.dwAvailPhys / 1024 / 1024;
		sprintf(str, "可用内存 %dMB", availmb);
		WriteToLog(str);
		Sleep(SLEEP_TIME);
	}
	WriteToLog("停止服务");
}

void WINAPI CtrlHandler(DWORD request)
{
	switch (request)
	{
	case SERVICE_CONTROL_STOP:
		brun = false;
		servicestatus.dwCurrentState = SERVICE_STOPPED;
		break;

	case SERVICE_CONTROL_SHUTDOWN:
		brun = false;
		servicestatus.dwCurrentState = SERVICE_STOPPED;
		break;

	default:
		break;
	}

	SetServiceStatus(hstatus, &servicestatus);
}



int _tmain(int argc, _TCHAR* argv[])
{

	SERVICE_TABLE_ENTRY entrytable[2];

	entrytable[0].lpServiceName = "testservice";

	entrytable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

	entrytable[1].lpServiceName = NULL;

	entrytable[1].lpServiceProc = NULL;

	StartServiceCtrlDispatcher(entrytable);

	return 0;
}

文章如无特别注明均为原创! 作者: admin, 转载或复制请以 超链接形式 并注明出处 万捷博客
原文地址《 C++写windows系统服务示例[源码]》发布于2018-11-18

打赏作者

评论

游客

看不清楚?点图切换
切换注册

登录

您也可以使用第三方帐号快捷登录

切换登录

注册