C++編寫Windows服務程式

來源:互聯網
上載者:User
#include "windows.h"SERVICE_STATUS          gSvcStatus;  //服務狀態SERVICE_STATUS_HANDLE   gSvcStatusHandle; //服務狀態控制代碼HANDLE                  ghSvcStopEvent = NULL;//服務停止控制代碼#define SERVER_NAME    TEXT("my_server") //服務名VOID WINAPI ServerMain( DWORD, LPTSTR *); //服務進入點void ServerReportEvent(LPTSTR szName,LPTSTR szFunction); //寫Windows日誌VOID ReportSvcStatus( DWORD, DWORD, DWORD ); //服務狀態和SCM互動VOID WINAPI SvcCtrlHandler( DWORD );  //SCM回呼函數VOID ServerProgram(DWORD, LPTSTR *); //服務主程式void main(){     SERVICE_TABLE_ENTRY DispatchTable[] =    {        { SERVER_NAME, (LPSERVICE_MAIN_FUNCTION)Server_main },        { NULL, NULL }    };        if (!StartServiceCtrlDispatcher(DispatchTable))    {         ServerReportEvent(SERVER_NAME,TEXT("StartServiceCtrlDispatcher"));    }}static VOID WINAPI Server_main(DWORD dwArgc, LPTSTR *lpszArgv ){    // Register the handler function for the service    gSvcStatusHandle = RegisterServiceCtrlHandler(         SERVER_NAME,         SvcCtrlHandler);        if( !gSvcStatusHandle )    {        ServerReportEvent(SERVER_NAME,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.    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 );        // TO_DO: Perform work until service stops.     ServerProgram(dwArgc, lpszArgv); //你需要的操作在此添加代碼        while(1)    {          // Check whether to stop the service.      WaitForSingleObject(ghSvcStopEvent, INFINITE);      ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );      return;    }  }void ServerReportEvent(LPTSTR szName,LPTSTR szFunction) {     HANDLE hEventSource;    LPCTSTR lpszStrings[2];    unsigned int len = sizeof(szFunction);    TCHAR *Buffer = new TCHAR[len];        hEventSource = RegisterEventSource(NULL, szName);        if( NULL != hEventSource )    {        //StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());        strcpy(Buffer,szFunction);        lpszStrings[0] = szName;        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);    }}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);                return;            case SERVICE_CONTROL_INTERROGATE:         // Fall through to send current status.        break;             default:         break;    }     ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.