win32控制台变服务代码

Posted 木木ing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了win32控制台变服务代码相关的知识,希望对你有一定的参考价值。

1、服务的主函数以及以及函数的声明,全局变量的定义

#define SERVICE_NAME "srv_follow"

SERVICE_STATUS g_ServiceStatus;
SERVICE_STATUS_HANDLE g_hServiceStatusHandle;
void WINAPI service_main(int argc, char** argv);
void WINAPI ServiceHandler(DWORD fdwControl);

 

//服务的主函数;
int _tmain(int argc, _TCHAR* argv[])
{
    //设置服务程序所在的地址;
    TCHAR  path[MAX_PATH] = {0};
    GetModuleFileName(NULL,path,MAX_PATH);
    _stprintf(path,_T("%s//..//"),path);
    SetCurrentDirectory(path);

    //设置服务表;
    SERVICE_TABLE_ENTRY ServiceTable[2];
    //设置服务到服务表;
    ServiceTable[0].lpServiceName = _T(SERVICE_NAME);  
    ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)service_main;
    //表的最后元素必须为NULL;
    ServiceTable[1].lpServiceName = NULL;  
    ServiceTable[1].lpServiceProc = NULL;

    //服务分派到服务控制管理器;
    StartServiceCtrlDispatcher(ServiceTable);
    Logger::getInstance()->info(__FILE__,__LINE__,"StartServiceCtrlDispatcher success!");
    DWORD err = GetLastError();


    return 0;
}

2、service_main函数

void WINAPI service_main(int argc, char** argv)
{
    //SERVICE_WIN32_OWN_PROCESS
    g_ServiceStatus.dwServiceType        = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwCurrentState       = SERVICE_START_PENDING;
    g_ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
    g_ServiceStatus.dwWin32ExitCode      = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint         = 0;
    g_ServiceStatus.dwWaitHint           = 0;
    g_hServiceStatusHandle = RegisterServiceCtrlHandler(_T(SERVICE_NAME), ServiceHandler);
    if (g_hServiceStatusHandle==0)
    {
        DWORD nError = GetLastError();
    }
    //add your init code here  这里是程序入口

    // Initialization complete - report running status
    g_ServiceStatus.dwCurrentState       = SERVICE_RUNNING;
    g_ServiceStatus.dwCheckPoint         = 0;
    g_ServiceStatus.dwWaitHint           = 9000;
    if(!SetServiceStatus(g_hServiceStatusHandle, &g_ServiceStatus))
    {
        DWORD nError = GetLastError();
    }
}

3、ServiceHandler函数

void WINAPI ServiceHandler(DWORD fdwControl)
{
    switch(fdwControl)
    {
    case SERVICE_CONTROL_STOP:
    case SERVICE_CONTROL_SHUTDOWN:
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCurrentState  = SERVICE_STOPPED;
        g_ServiceStatus.dwCheckPoint    = 0;
        g_ServiceStatus.dwWaitHint      = 0;
        //add you quit code here  这里释放资源
        
        break;
    default:
        return;
    };
    if (!SetServiceStatus(g_hServiceStatusHandle,  &g_ServiceStatus))
    {
        DWORD nError = GetLastError();
    }
}

 

以上就是把win32改为后台服务所需要的代码。

以上是关于win32控制台变服务代码的主要内容,如果未能解决你的问题,请参考以下文章

与 Win32 服务的进程间通信

如何在 Win32 控制台应用程序中将 argv[] 设置为不区分大小写?

更改整个控制台背景颜色 (Win32 C++)

python将文本转换成语音的代码

从 Win32 控制台应用程序驱动 MFC 应用程序

win32——小知识点