首页 > 系统相关 >【C++】将 C++ 程序 以 Windows Service 服务部署

【C++】将 C++ 程序 以 Windows Service 服务部署

时间:2023-12-23 23:32:23浏览次数:33  
标签:服务 Service SvcInit Windows VOID C++ int DWORD include


服务主函数

1)先进行安装 your_program.exe install 2) 在进入电脑管理-服务,进行启动
3)若要多启动方式,在下面主函数中,进行启动类别判断是服务形式启动还是控制台程序启动

int __cdecl _tmain(int argc, TCHAR* argv[])

服务代码

作为程序入口代码,将自己程序的主函数代码,访入 SvcInit 函数中,见SvcInit 注释内容

#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#include <iostream>

#pragma comment(lib, "advapi32.lib")

#define SVCNAME TEXT("SSSSSSSSSSS")

SERVICE_STATUS          gSvcStatus;
SERVICE_STATUS_HANDLE   gSvcStatusHandle;
HANDLE                  ghSvcStopEvent = NULL;

VOID SvcInstall(void);
VOID WINAPI SvcCtrlHandler(DWORD);
VOID WINAPI SvcMain(DWORD, LPTSTR*);

VOID ReportSvcStatus(DWORD, DWORD, DWORD);
VOID SvcInit(DWORD, LPTSTR*);
VOID SvcReportEvent(LPCTSTR);

#define SVC_ERROR -11

int __cdecl _tmain(int argc, TCHAR* argv[])
{
    // If command-line parameter is "install", install the service. 
    // Otherwise, the service is probably being started by the SCM.
    


    std::cout << *argv[1] << " , " <<  *argv[2] << " , " << *argv[3] << std::endl;
    if (lstrcmpi(argv[1], TEXT("install")) == 0)
    {
        SvcInstall();
        return 0;
    }
    TCHAR svcname[] = SVCNAME;
    // TO_DO: Add any additional services for the process to this table.
    SERVICE_TABLE_ENTRY DispatchTable[] =
    {
        { svcname, (LPSERVICE_MAIN_FUNCTION)SvcMain },
        { NULL, NULL }
    };

    // This call returns when the service has stopped. 
    // The process should simply terminate when the call returns.

    if (!StartServiceCtrlDispatcher(DispatchTable))
    {
        SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
    }
    return 0;
}

VOID SvcInstall()
{
    SC_HANDLE schSCManager;
    SC_HANDLE schService;
    TCHAR szPath[MAX_PATH];

    if (!GetModuleFileName(NULL, szPath, MAX_PATH))
    {
        printf("Cannot install service (%d)\n", GetLastError());
        return;
    }

    // Get a handle to the SCM database. 

    schSCManager = OpenSCManager(
        NULL,                    // local computer
        NULL,                    // ServicesActive database 
        SC_MANAGER_ALL_ACCESS);  // full access rights 

    if (NULL == schSCManager)
    {
        printf("OpenSCManager failed (%d)\n", GetLastError());
        return;
    }

    // Create the service

    schService = CreateService(
        schSCManager,              // SCM database 
        SVCNAME,                   // name of service 
        SVCNAME,                   // service name to display 
        SERVICE_ALL_ACCESS,        // desired access 
        SERVICE_WIN32_OWN_PROCESS, // service type 
        SERVICE_DEMAND_START,      // start type 
        SERVICE_ERROR_NORMAL,      // error control type 
        szPath,                    // path to service's binary 
        NULL,                      // no load ordering group 
        NULL,                      // no tag identifier 
        NULL,                      // no dependencies 
        NULL,                      // LocalSystem account 
        NULL);                     // no password 

    if (schService == NULL)
    {
        printf("CreateService failed (%d)\n", GetLastError());
        CloseServiceHandle(schSCManager);
        return;
    }
    else printf("Service installed successfully\n");

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);
}


VOID WINAPI SvcMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
    // Register the handler function for the service

    gSvcStatusHandle = RegisterServiceCtrlHandler(
        SVCNAME,
        SvcCtrlHandler);

    if (!gSvcStatusHandle)
    {
        SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
        return;
    }

    // These SERVICE_STATUS members remain as set here

    gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    gSvcStatus.dwServiceSpecificExitCode = 0;

    // Report initial status to the SCM

    ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);

    // Perform service-specific initialization and work.

    SvcInit(dwArgc, lpszArgv);
}

VOID SvcInit(DWORD dwArgc, LPTSTR* lpszArgv)
{
    // TO_DO: Declare and set any required variables.
    //   Be sure to periodically call ReportSvcStatus() with 
    //   SERVICE_START_PENDING. If initialization fails, call
    //   ReportSvcStatus with SERVICE_STOPPED.

    // Create an event. The control handler function, SvcCtrlHandler,
    // signals this event when it receives the stop control code.

    ghSvcStopEvent = CreateEvent(
        NULL,    // default security attributes
        TRUE,    // manual reset event
        FALSE,   // not signaled
        NULL);   // no name

    if (ghSvcStopEvent == NULL)
    {
        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
        return;
    }

    // Report running status when initialization is complete.

    ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);

    /// <summary>
    /// 这里引入你的主函数,用于服务形式运行
    /// 1) 服务安装;
    /// 2) 服务运行;
    /// </summary>
    /// <param name="dwArgc"></param>
    /// <param name="lpszArgv"></param>
    std::cout << "hillo service" << std::endl;

    // TO_DO: Perform work until service stops.
    while (1)
    {
        // Check whether to stop the service.

        WaitForSingleObject(ghSvcStopEvent, INFINITE);

        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
        return;
    }
}


VOID ReportSvcStatus(DWORD dwCurrentState,
    DWORD dwWin32ExitCode,
    DWORD dwWaitHint)
{
    static DWORD dwCheckPoint = 1;

    // Fill in the SERVICE_STATUS structure.

    gSvcStatus.dwCurrentState = dwCurrentState;
    gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
    gSvcStatus.dwWaitHint = dwWaitHint;

    if (dwCurrentState == SERVICE_START_PENDING)
        gSvcStatus.dwControlsAccepted = 0;
    else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;

    if ((dwCurrentState == SERVICE_RUNNING) ||
        (dwCurrentState == SERVICE_STOPPED))
        gSvcStatus.dwCheckPoint = 0;
    else gSvcStatus.dwCheckPoint = dwCheckPoint++;

    // Report the status of the service to the SCM.
    SetServiceStatus(gSvcStatusHandle, &gSvcStatus);
}


VOID WINAPI SvcCtrlHandler(DWORD dwCtrl)
{
    // Handle the requested control code. 

    switch (dwCtrl)
    {
    case SERVICE_CONTROL_STOP:
        ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);

        // Signal the service to stop.


        SetEvent(ghSvcStopEvent);
        ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);

        return;

    case SERVICE_CONTROL_INTERROGATE:
        break;

    default:
        break;
    }

}


VOID SvcReportEvent(LPCTSTR szFunction)
{
    HANDLE hEventSource;
    LPCTSTR lpszStrings[2];
    TCHAR Buffer[80];

    hEventSource = RegisterEventSource(NULL, SVCNAME);

    if (NULL != hEventSource)
    {
        StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());

        lpszStrings[0] = SVCNAME;
        lpszStrings[1] = Buffer;

        ReportEvent(hEventSource,        // event log handle
            EVENTLOG_ERROR_TYPE, // event type
            0,                   // event category
            SVC_ERROR,           // event identifier
            NULL,                // no security identifier
            2,                   // size of lpszStrings array
            0,                   // no binary data
            lpszStrings,         // array of strings
            NULL);               // no binary data

        DeregisterEventSource(hEventSource);
    }
}


标签:服务,Service,SvcInit,Windows,VOID,C++,int,DWORD,include
From: https://blog.51cto.com/u_15976424/8947914

相关文章

  • 检查Windows更新问题解决
    在任务栏搜索框输入cmd,点击右侧的“以管理员身份运行”,打开后输入:(建议复制粘贴,防止输入有误出现错误提示等请忽略*)SCconfigwuauservstart=auto回车(Enter按键)SCconfigbitsstart=auto回车(Enter按键)SCconfigcryptsvcstart=auto回车(Enter按键)SCconfigtrustedin......
  • C++简单实现list链表数据结构(一)
    链表(list)是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的。链表的组成:链表由一系列结点组成结点的组成:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域C++STL中的链表是一个双向循环链表由于链表的存储方式并不是连续的内存空......
  • C++知识点总结
    第二章1.基本数据类型int有16位,即两个字节,char只占一个字节。在VisualC++6.0中,对float提供6位有效数字,对double提供15位有效数字,并且float和double的数值范围不同。对float分配4个字节,对double和longdouble分配8个字节。2.常变量关键字const。变量的值在程序运行期间不能改......
  • 手机平板远程访问kvm虚拟机的windows
    title:手机平板远程访问kvm虚拟机的windowsbanner_img:https://cdn.studyinglover.com/pic/2023/12/5c4ffb4ee8500a9cdfa2406137e5e0a8.jpgdate:2023-12-2319:28:00tags:-踩坑手机平板远程访问kvm虚拟机的windows最近快期末周了,开始陆陆续续开始复习(预习)这学期的课,......
  • C++:最大值最小值及其索引
    std::max_element和std::min_element 是C++标准库<algorithm>中的函数,可以得到数组和向量(vector)的最值及其索引intcard[6]={1,2,3,4,5,6}intmaxValue=*max_element(card.begin(),card.end());intminValue=*min_element(card.begin(),card.end());intmaxPositi......
  • Java登陆第二十九天——Servlet继承关系,service和doGet的区别
    Servlet继承关系树:Servlet接口查看Servlet源码publicinterfaceServlet{voidinit(ServletConfigvar1)throwsServletException;ServletConfiggetServletConfig();voidservice(ServletRequestvar1,ServletResponsevar2)throwsServletException,I......
  • git安装(Windows)
    首先进入官网——https://git-scm.com/download选择Windows,根据自己电脑情况选择需要的版本(我是64位)点击安装 --------------------这里不知道为什么在官网没有下载下来,所以从网盘下载的:https://blog.csdn.net/weixin_50212044/article/details/131433207下好之后......
  • C++ --- 函数重载
    什么是函数重载函数重载: 是函数的一种特殊情况,C++允许在同一作用域中声明几个功能类似的同名函数,这些同名函数的形参列表(参数个数或类型或顺序)必须不同,常用来处理实现功能类似数据类型不同的问题。函数重载是C++在C语言基础上进行的改进,解决了C语言同名函数无法服务不同类型......
  • C++U5-11-特殊二叉树
    学习目标 完全二叉树:二又树拥有的性质,在完全二叉树中都拥有 性质 练习1 练习2 练习3编程题:[完全二叉树的叶子结点]【算法分析】递归,前序遍历输出。【参考代码】#include<iostream>usingnamespacestd;constintSIZE=1010;structnode{......
  • 设计模式<c++> (1)策略模式
    一、定义策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。二、使用场景客户需要很多种鸭子。要求:1.每种鸭子都要会游泳。2.每种鸭子有叫和飞的行为。3.鸭子的叫和飞的行为可以在使用......