win32 c++编写系统服务程序

首先先创建一个控制台程序,或者win32程序,都没关系。因为后台服务是看不到界面的。
服务程序应具有这样的功能:
一个服务主函数,注册服务控制句柄,启动要运行的代码。
二是服务控制函数,注册给系统,提供对服务管理程序SCM的响应,就是我的电脑-》管理里面的服务,不是有开始,停止,暂停这些功能么,这个函数就是对这个响应,停止的时候就做退出清理工作,关闭进程。
就两个函数而已。一般是ServiceMain 和ServiceCtrlHandler
这就是服务的全部必须代码了。
然后为什么别人的服务还有很多函数呢,什么 InstallService DeleteService之类的。
因为服务需要安装呀,一般一个程序写在一起,方便一点,但安装服务不是服务必须的,这必须理清楚,服务只需要一个主函数就行,安装卸载可以由其他的程序安装卸载。比如sc 或者直接操作注册表。
下面就是贴代码了
// GtServ.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Windows.h" 
#include "LogWriter.h"
SERVICE_STATUS m_ServiceStatus; 
SERVICE_STATUS_HANDLE m_ServiceStatusHandle; 
BOOL bRunning=true; 
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv); 
void WINAPI ServiceCtrlHandler(DWORD Opcode); 
BOOL InstallService(); 
BOOL DeleteService(); 
//log类
CLogWriter log("D:\\log.TXT");
void DoTask() 
{
 
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    
    if(argc>1) 
    { 
        if( wcscmp(argv[1],L"-i")==0) 
        { 
        if(InstallService()) 
        printf("\n Service Installed Sucessfully\n"); 
        else 
        printf("\n Service has been installed\n"); 
        } 
        else if(wcscmp(argv[1],L"-d")==0) 
        { 
            if(DeleteService()) 
            printf("\n Service UnInstalled Sucessfully\n"); 
            else 
            printf("\nInstalled Easin Central Service Not Found\n"); 
        }
        else 
        { 
            printf("\nUnknown Switch Usage\nFor Install use Servicetest -i\nFor UnInstall use Servicetest -d\n"); 
        } 
    } 
    else 
    { 
        SERVICE_TABLE_ENTRY DispatchTable[]={{L"GtServ",ServiceMain},{NULL,NULL}};   
        StartServiceCtrlDispatcher(DispatchTable);  
    } 
    
    return 0; 
}
 
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv) 
{ 
//     DWORD status;  
//     DWORD specificError;  
      m_ServiceStatus.dwServiceType          = SERVICE_WIN32;  
      m_ServiceStatus.dwCurrentState         = SERVICE_START_PENDING;  
      m_ServiceStatus.dwControlsAccepted     = SERVICE_ACCEPT_STOP;  
      m_ServiceStatus.dwWin32ExitCode        = 0;  
      m_ServiceStatus.dwServiceSpecificExitCode = 0;  
      m_ServiceStatus.dwCheckPoint           = 0;  
      m_ServiceStatus.dwWaitHint             = 0;  
 
      m_ServiceStatusHandle = RegisterServiceCtrlHandler(L"GtServ",ServiceCtrlHandler);   
      if (m_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)  
      {  
          return;  
      }      
      m_ServiceStatus.dwCurrentState         = SERVICE_RUNNING;  
      m_ServiceStatus.dwCheckPoint           = 0;  
      m_ServiceStatus.dwWaitHint             = 0;   
      if (!SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus))  
      {  
      }  
    bRunning=true; 
    while(bRunning) 
    {    
    Sleep(3000); 
    //Place Your Code for processing here....   
    DoTask(); 
    } 
      return;  
} 
 
void WINAPI ServiceCtrlHandler(DWORD Opcode) 
{ 
      switch(Opcode)  
      {  
          case SERVICE_CONTROL_PAUSE:  
              m_ServiceStatus.dwCurrentState = SERVICE_PAUSED;  
              break;  
 
          case SERVICE_CONTROL_CONTINUE:  
              m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;  
              break;  
          case SERVICE_CONTROL_STOP:  
              m_ServiceStatus.dwWin32ExitCode = 0;  
              m_ServiceStatus.dwCurrentState    = SERVICE_STOPPED;     
              m_ServiceStatus.dwCheckPoint      = 0;  
              m_ServiceStatus.dwWaitHint        = 0;     
              SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus); 
     bRunning=false; 
     break; 
          case SERVICE_CONTROL_INTERROGATE:  
              break;  
      }       
      return;  
} 
BOOL InstallService() 
{ 
    WCHAR strDir[1024]; 
    SC_HANDLE schSCManager,schService; 
    GetCurrentDirectory(1024,strDir); 
    lstrcat(strDir,L"\\GtServ.exe");  
    schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);   
 
    if (schSCManager == NULL)  
    return false; 
      LPCTSTR lpszBinaryPathName=strDir; 
      schService = CreateService((struct SC_HANDLE__ *)schSCManager,L"GtServ",L"GtServ",             // service name to display  
          SERVICE_ALL_ACCESS,          // desired access  
          SERVICE_WIN32_OWN_PROCESS, // service type  
          SERVICE_AUTO_START,        // start type  
          SERVICE_ERROR_NORMAL,        // error control type  
          lpszBinaryPathName,          // service's binary  
          NULL,                        // no load ordering group  
          NULL,                        // no tag identifier  
          NULL,                        // no dependencies  
          NULL,                        // LocalSystem account  
          NULL);                       // no password  
     if (schService == NULL)  
          return false;   
    SERVICE_DESCRIPTION   sdBuf; 
    sdBuf.lpDescription   =   L"GT即时同步软件后台服务"; 
    ChangeServiceConfig2( schService, SERVICE_CONFIG_DESCRIPTION, &sdBuf); 
     CloseServiceHandle((struct SC_HANDLE__ *)schService);  
    return true; 
} 
BOOL DeleteService() 
{ 
    HANDLE schSCManager; 
    SC_HANDLE hService; 
    schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); 
 
    if (schSCManager == NULL)  
        return false;  
    hService=OpenService((struct SC_HANDLE__ *)schSCManager,L"GtServ",SERVICE_ALL_ACCESS); 
    if (hService == NULL)  
        return false; 
    if(DeleteService(hService)==0) 
        return false; 
    if(CloseServiceHandle(hService)==0) 
        return false; 
    else 
        return true; 
} 


你可能感兴趣的:(C++)