1. 程式人生 > >C服務程序模板

C服務程序模板

ecif 處理 控制 poi 結束 stopped etl 狀態 .cn

在DoWork中添加自己的代碼。
  1. #include <windows.h>
  2. SERVICE_STATUS ServiceStatus;
  3. SERVICE_STATUS_HANDLE hStatus;
  4. VOID WINAPI ServiceMain( DWORD dwArgc, LPTSTR *lpszArgv );
  5. VOID WINAPI ServiceHandler( DWORD fdwControl );
  6. int main(int argc,char** argv)
  7. {
  8. SERVICE_TABLE_ENTRY ServiceTable[2];
  9. ServiceTable[0].lpServiceName=”SrvSample”;
  10. ServiceTable[0].lpServiceProc=(LPSERVICE_MAIN_FUNCTION)ServiceMain;
  11. ServiceTable[1].lpServiceName=NULL;
  12. ServiceTable[1].lpServiceProc=NULL;
  13. StartServiceCtrlDispatcher
    (ServiceTable);
  14. return 0;
  15. }
  16. //服務控制處理函數
  17. VOID WINAPI ServiceHandler(DWORD fdwControl)
  18. {
  19. switch(fdwControl)
  20. {
  21. case SERVICE_CONTROL_PAUSE:
  22. ServiceStatus.dwCurrentState = SERVICE_PAUSED;
  23. break
    ;
  24. case SERVICE_CONTROL_CONTINUE:
  25. ServiceStatus.dwCurrentState = SERVICE_RUNNING;
  26. break;
  27. case SERVICE_CONTROL_STOP:
  28. case SERVICE_CONTROL_SHUTDOWN:
  29. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  30. ServiceStatus.dwWin32ExitCode = 0;
  31. ServiceStatus.dwCheckPoint = 0;
  32. ServiceStatus.dwWaitHint = 0;
  33. SetServiceStatus(hStatus,&ServiceStatus);
  34. return ;
  35. case SERVICE_CONTROL_INTERROGATE:
  36. break;
  37. default:
  38. break;
  39. }
  40. SetServiceStatus(hStatus,&ServiceStatus);
  41. return ;
  42. }
  43. //服務主函數
  44. VOID WINAPI ServiceMain( DWORD dwArgc, LPTSTR *lpszArgv )
  45. {
  46. DWORD status = 0;
  47. DWORD specificError = 0xfffffff;
  48. ServiceStatus.dwServiceType = SERVICE_WIN32;
  49. ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
  50. ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
  51. ServiceStatus.dwWin32ExitCode = 0;
  52. ServiceStatus.dwServiceSpecificExitCode = 0;
  53. ServiceStatus.dwCheckPoint = 0;
  54. ServiceStatus.dwWaitHint = 0;
  55. hStatus=RegisterServiceCtrlHandler("SrvSample",
  56. (LPHANDLER_FUNCTION)ServiceHandler);
  57. if (hStatus==0)
  58. return;
  59. // Handle error condition
  60. status = GetLastError();
  61. if (status!=NO_ERROR)
  62. {
  63. ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  64. ServiceStatus.dwCheckPoint = 0;
  65. ServiceStatus.dwWaitHint = 0;
  66. ServiceStatus.dwWin32ExitCode = status;
  67. ServiceStatus.dwServiceSpecificExitCode = specificError;
  68. SetServiceStatus(hStatus, &ServiceStatus);
  69. return;
  70. }
  71. // 初始化結束,報告運行狀態
  72. ServiceStatus.dwCurrentState = SERVICE_RUNNING;
  73. ServiceStatus.dwCheckPoint = 0;
  74. ServiceStatus.dwWaitHint = 0;
  75. SetServiceStatus(hStatus, &ServiceStatus);
  76. //在這裏做其他的工作
  77. DoWork();
  78. }




null

C服務程序模板