C++程序服务化封装

2024-06-02 22:32
文章标签 c++ 程序 封装 服务化

本文主要是介绍C++程序服务化封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前有一篇“C++exe做系统服务,自动加载”是C语言风格的方式,使用是没有问题,但是很杂乱,这里对之封装,简化使用方式。

WindowsService.h

#pragma once
#include <string>
using namespace std;//注入Windows服务类
class CWindowsService
{
public:CWindowsService();//构造函数CWindowsService(const string strServiceName);//构造函数~CWindowsService();//析构函数void SetServiceName(const string strServiceName);//设置服务名称(所有操作前必须调用)void Run();//一键自助安装服务   private:bool Install(int & dwCurrentState);//安装服务bool Uninstall();//卸载服务bool Start();//启动服务bool Stop();//停止服务static void ServiceMain(DWORD argc, LPTSTR *argv);//创建服务主要处理逻辑static void ServiceCtrlHandler(DWORD nControlCode);//接受servicecontrol 命令BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint);//更新服务状态 更新失败即结束服务BOOL StartServiceThread();//创建主窗口线程static DWORD ServiceExecutionThread(LPDWORD param);//创建服务主线程void KillService();// 停止服务 即结束主窗口线程 设置状态失败或是收到STOP SERVICE 命令调用此函数private:HANDLE m_hServiceThread;SERVICE_STATUS_HANDLE m_nServiceStatusHandle;HANDLE m_EventkillService;HWND m_hMain;BOOL m_bServiceRunning;DWORD m_dwServiceCurrentStatus;string m_ServiceDisplayName;string m_ServiceName;
};extern CWindowsService *g_pWindowsService;

WindowsService.cpp

#include "stdafx.h"
#include "WindowsService.h"
#include "server.h"CWindowsService *g_pWindowsService = NULL;//构造函数
CWindowsService::CWindowsService()
{m_hServiceThread = 0;m_nServiceStatusHandle = 0;m_EventkillService = NULL;m_hMain = NULL;m_bServiceRunning = FALSE;m_dwServiceCurrentStatus = 0;
}CWindowsService::CWindowsService(const string strServiceName)
{CWindowsService();m_ServiceDisplayName = strServiceName;m_ServiceName = strServiceName;
}//析构函数
CWindowsService::~CWindowsService()
{
}//设置服务名称
void CWindowsService::SetServiceName(const string strServiceName)
{m_ServiceDisplayName = strServiceName;m_ServiceName = strServiceName;
}//一键自助安装服务
void CWindowsService::Run()
{BOOL bNT = FALSE;BOOL bInstalled = FALSE;int dwCurrentState = 0;SC_HANDLE hService, hScm;hScm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);if (hScm){bNT = TRUE;hService = OpenService(hScm, m_ServiceName.c_str(), GENERIC_READ);if (hService){bInstalled = TRUE;SERVICE_STATUS ServiceStatus;if (QueryServiceStatus(hService, &ServiceStatus)){dwCurrentState = ServiceStatus.dwCurrentState;if (dwCurrentState == SERVICE_START_PENDING){CloseServiceHandle(hService);CloseServiceHandle(hScm);char chServiceName[256] = "";strcpy_s(chServiceName, m_ServiceName.c_str());const SERVICE_TABLE_ENTRY servicetable[] ={{ chServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain },{ NULL,NULL }};BOOL success;success = StartServiceCtrlDispatcher(servicetable);if (!success){int nError = GetLastError();TCHAR buffer[1000];_stprintf_s(buffer, _T("启动服务出错,错误码:%d"), nError);MessageBox(0, buffer, m_ServiceName.c_str(), MB_OK);}return ;}}CloseServiceHandle(hService);}CloseServiceHandle(hScm);}if (!bInstalled){if (MessageBox(0, _T("是否安装服务?"), m_ServiceName.c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES){if (!Install(dwCurrentState)){MessageBox(0, _T("安装服务失败"), m_ServiceName.c_str(), MB_OK);return;}}elsereturn ;}if (dwCurrentState == SERVICE_STOPPED && (MessageBox(0, _T("启动服务?"), m_ServiceName.c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES)){if (!Start()){MessageBox(0, _T("启动服务失败"), m_ServiceName.c_str(), MB_OK);}return;}if (dwCurrentState == SERVICE_STOPPED && (MessageBox(0, _T("卸载服务?"), m_ServiceName.c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES)){if (!Uninstall()){MessageBox(0, _T("卸载服务失败"), m_ServiceName.c_str(), MB_OK);}return ;}if (dwCurrentState != SERVICE_STOPPED && (MessageBox(0, _T("停止服务?"), m_ServiceName.c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES)){if (!Stop()){MessageBox(0, _T("停止服务失败"), m_ServiceName.c_str(), MB_OK);}return;}if (dwCurrentState == SERVICE_STOPPED)return ;
}//安装服务
bool CWindowsService::Install(int & dwCurrentState)
{SC_HANDLE hService, hScm;hScm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);if (!hScm){return false;}int nStartMode = SERVICE_AUTO_START;if (MessageBox(0, _T("自动运行服务?"), m_ServiceName.c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES){nStartMode = SERVICE_AUTO_START;}TCHAR buffer[MAX_PATH + 3];buffer[0] = '"';DWORD written = GetModuleFileName(0, buffer + 1, MAX_PATH);if (!written){CloseServiceHandle(hScm);MessageBox(0, _T("创建服务失败,未能获取应用程序当前的路径"), m_ServiceName.c_str(), MB_ICONSTOP);return false;}buffer[written + 1] = '"';buffer[written + 2] = 0;hService = CreateService(hScm, m_ServiceName.c_str(),m_ServiceDisplayName.c_str(),SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, nStartMode,SERVICE_ERROR_NORMAL,buffer,0, 0, NULL, 0, 0);if (!hService){CloseServiceHandle(hScm);return false;}SERVICE_DESCRIPTION description;memset(&description, 0, sizeof(SERVICE_DESCRIPTION));TCHAR szdescription[100];memset(szdescription, 0, sizeof(TCHAR) * 100);_stprintf_s(szdescription, 100, _T("%s"), m_ServiceName.c_str());//服务名称description.lpDescription = szdescription;ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &description);CloseServiceHandle(hService);CloseServiceHandle(hScm);dwCurrentState = SERVICE_STOPPED;return true;
}//卸载服务
bool CWindowsService::Uninstall()
{SC_HANDLE hService, hScm;hScm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);if (!hScm){return false;}hService = OpenService(hScm, m_ServiceName.c_str(), SERVICE_ALL_ACCESS);if (!hService){CloseServiceHandle(hScm);return false;}DeleteService(hService);CloseServiceHandle(hService);CloseServiceHandle(hScm);return true;
}//启动服务
bool CWindowsService::Start()
{SC_HANDLE hService, hScm;hScm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);if (!hScm){return false;}hService = OpenService(hScm, m_ServiceName.c_str(), SERVICE_ALL_ACCESS);if (!hService){CloseServiceHandle(hScm);return false;}if (StartService(hService, 0, NULL) == 0){DWORD dwerr = GetLastError();Sleep(1);}CloseServiceHandle(hService);CloseServiceHandle(hScm);return true;
}//停止服务
bool CWindowsService::Stop()
{SC_HANDLE hService, hScm;hScm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);if (!hScm){return false;}hService = OpenService(hScm, m_ServiceName.c_str(), SERVICE_ALL_ACCESS);if (!hService){CloseServiceHandle(hScm);return false;}SERVICE_STATUS status;ControlService(hService, SERVICE_CONTROL_STOP, &status);CloseServiceHandle(hService);CloseServiceHandle(hScm);return true;
}//创建服务主要处理逻辑
void CWindowsService::ServiceMain(DWORD argc, LPTSTR * argv)
{BOOL success;g_pWindowsService->m_nServiceStatusHandle = RegisterServiceCtrlHandler(g_pWindowsService->m_ServiceName.c_str(), (LPHANDLER_FUNCTION)(ServiceCtrlHandler));if (!g_pWindowsService->m_nServiceStatusHandle)return;success = g_pWindowsService->UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 3000);if (!success)return;g_pWindowsService->m_EventkillService = CreateEvent(0, TRUE, FALSE, 0);//创建时间等待结束if (g_pWindowsService->m_EventkillService == NULL)return;success = g_pWindowsService->UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);if (!success)return;success = g_pWindowsService->StartServiceThread(); //开启主线程if (!success)return;g_pWindowsService->m_dwServiceCurrentStatus = SERVICE_RUNNING;success = g_pWindowsService->UpdateServiceStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);if (!success)return;WaitForSingleObject(g_pWindowsService->m_EventkillService, INFINITE); //等待结束CloseHandle(g_pWindowsService->m_EventkillService);WaitForSingleObject(g_pWindowsService->m_hServiceThread, INFINITE); // 更待结束线程结束CloseHandle(g_pWindowsService->m_hServiceThread);g_pWindowsService->UpdateServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
}//接受servicecontrol 命令
void CWindowsService::ServiceCtrlHandler(DWORD nControlCode)
{BOOL success;switch (nControlCode){case SERVICE_CONTROL_SHUTDOWN:case SERVICE_CONTROL_STOP:g_pWindowsService->m_dwServiceCurrentStatus = SERVICE_STOP_PENDING;success = g_pWindowsService->UpdateServiceStatus(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 3000);g_pWindowsService->KillService();return;default:break;}g_pWindowsService->UpdateServiceStatus(g_pWindowsService->m_dwServiceCurrentStatus, NO_ERROR, 0, 0, 0);
}//更新服务状态 更新失败即结束服务
BOOL CWindowsService::UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint)
{BOOL success;SERVICE_STATUS nServiceStatus;nServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;nServiceStatus.dwCurrentState = dwCurrentState;if (dwCurrentState == SERVICE_START_PENDING){nServiceStatus.dwControlsAccepted = 0;}else{nServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP| SERVICE_ACCEPT_SHUTDOWN;}if (dwServiceSpecificExitCode == 0){nServiceStatus.dwWin32ExitCode = dwWin32ExitCode;}else{nServiceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;}nServiceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;nServiceStatus.dwCheckPoint = dwCheckPoint;nServiceStatus.dwWaitHint = dwWaitHint;success = SetServiceStatus(m_nServiceStatusHandle, &nServiceStatus);if (!success){KillService();return success;}else{return success;}
}//创建主窗口线程
BOOL CWindowsService::StartServiceThread()
{DWORD id;m_hServiceThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ServiceExecutionThread, 0, 0, &id);if (m_hServiceThread == 0){return FALSE;}else{m_bServiceRunning = TRUE;return true;}
}//创建服务主线程(应用主要启动)
DWORD CWindowsService::ServiceExecutionThread(LPDWORD param)
{BOOL res = TRUE;//启动CServer *pServer = new CServer;g_pWindowsService->m_bServiceRunning = pServer->Create();if (!g_pWindowsService->m_bServiceRunning){return 0;}else{g_pWindowsService->m_hMain = pServer->GetMainHwnd();}MSG msg;while (GetMessage(&msg, 0, 0, 0)){TranslateMessage(&msg);DispatchMessage(&msg);}SetEvent(g_pWindowsService->m_EventkillService);return 0;
}// 停止服务 即结束主窗口线程 设置状态失败或是收到STOP SERVICE 命令调用此函数
void CWindowsService::KillService()
{if (m_hMain != NULL)PostMessage(m_hMain, WM_CLOSE, 0, 0); //结束窗口m_bServiceRunning = FALSE;
}
  • 需要修改地方
    WindowsService.cpp
    //创建服务主线程(应用主要启动)
    DWORD CWindowsService::ServiceExecutionThread(LPDWORD param)
    修改该函数里面的
    //启动CServer *pServer = new CServer;g_pWindowsService->m_bServiceRunning = pServer->Create();

这里就是服务真正需要运行的代码,对应修改。

  • 调用方式

#include "stdafx.h"
#include "WindowsService.h"#ifndef _DEBUG
#pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" )
#endifint _tmain(int argc, _TCHAR* argv[])
{
#ifdef _DEBUG//调试//调试使用
#else//服务(发布使用)//设置服务名称string strServiceName = "ServiceName";g_pWindowsService = new CWindowsService(strServiceName);g_pWindowsService->Run();//注册服务,启动
#endifreturn 0;
}

这篇关于C++程序服务化封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1025273

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

java程序远程debug原理与配置全过程

《java程序远程debug原理与配置全过程》文章介绍了Java远程调试的JPDA体系,包含JVMTI监控JVM、JDWP传输调试命令、JDI提供调试接口,通过-Xdebug、-Xrunjdwp参数配... 目录背景组成模块间联系IBM对三个模块的详细介绍编程使用总结背景日常工作中,每个程序员都会遇到bu

uni-app小程序项目中实现前端图片压缩实现方式(附详细代码)

《uni-app小程序项目中实现前端图片压缩实现方式(附详细代码)》在uni-app开发中,文件上传和图片处理是很常见的需求,但也经常会遇到各种问题,下面:本文主要介绍uni-app小程序项目中实... 目录方式一:使用<canvas>实现图片压缩(推荐,兼容性好)示例代码(小程序平台):方式二:使用uni

C++读写word文档(.docx)DuckX库的使用详解

《C++读写word文档(.docx)DuckX库的使用详解》DuckX是C++库,用于创建/编辑.docx文件,支持读取文档、添加段落/片段、编辑表格,解决中文乱码需更改编码方案,进阶功能含文本替换... 目录一、基本用法1. 读取文档3. 添加段落4. 添加片段3. 编辑表格二、进阶用法1. 文本替换2

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

Python实现简单封装网络请求的示例详解

《Python实现简单封装网络请求的示例详解》这篇文章主要为大家详细介绍了Python实现简单封装网络请求的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录安装依赖核心功能说明1. 类与方法概览2.NetHelper类初始化参数3.ApiResponse类属性与方法使用实

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法