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++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

【C++高阶】C++类型转换全攻略:深入理解并高效应用

📝个人主页🌹:Eternity._ ⏩收录专栏⏪:C++ “ 登神长阶 ” 🤡往期回顾🤡:C++ 智能指针 🌹🌹期待您的关注 🌹🌹 ❀C++的类型转换 📒1. C语言中的类型转换📚2. C++强制类型转换⛰️static_cast🌞reinterpret_cast⭐const_cast🍁dynamic_cast 📜3. C++强制类型转换的原因📝

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

EMLOG程序单页友链和标签增加美化

单页友联效果图: 标签页面效果图: 源码介绍 EMLOG单页友情链接和TAG标签,友链单页文件代码main{width: 58%;是设置宽度 自己把设置成与您的网站宽度一样,如果自适应就填写100%,TAG文件不用修改 安装方法:把Links.php和tag.php上传到网站根目录即可,访问 域名/Links.php、域名/tag.php 所有模板适用,代码就不粘贴出来,已经打