码迷,mamicode.com
首页 > Windows程序 > 详细

VC Windows系统服务创建代码

时间:2016-03-07 13:56:08      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:

Windows系统服务创建步骤,常用类封装,废话不多说,直接上代码

技术分享
 1 // ServceDemo.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "WindwosService.h"
 6 
 7 unsigned __stdcall SvcRun (void *Params )
 8 {
 9     while(1)
10     {
11 
12         for (int i = 0;i < 100;i++)
13         {
14             printf("%d\n",i);
15         }
16 
17         ::Sleep(1*60*1000);
18     }
19     return 0;
20 }
21 
22 int _tmain(int argc, _TCHAR* argv[])
23 {
24 #ifdef WIN32
25     InitService(argc,argv);
26 #endif // WIN32
27 
28 #ifdef linux
29 
30 #endif // linux
31 
32     return 0;
33 }
main函数文件代码
技术分享
 1 #if !defined JX_About_Privilege
 2 #define JX_About_Privilege
 3 
 4 #include <Windows.h>
 5 // Windows提权类
 6 class JXAboutPrivilege
 7 {
 8 public:
 9     JXAboutPrivilege(void);
10     ~JXAboutPrivilege(void);
11     // 提升关机权限
12     static BOOL EnableShutdownPrivileges( VOID );
13     // 提升结束进程的权限
14     static BOOL EnableTermProcessPrivileges( VOID );
15     // 提升加载驱动的权限
16     static BOOL EnableLoadDriverPrivileges( VOID );
17 
18     static BOOL EnableDebugPrivilege(BOOL   fEnable);
19 };
20 
21 #endif
JXAboutPrivilege.h
技术分享
 1 #include "StdAfx.h"
 2 #include "JXAboutPrivilege.h"
 3 
 4 
 5 JXAboutPrivilege::JXAboutPrivilege(void)
 6 {
 7 }
 8 
 9 JXAboutPrivilege::~JXAboutPrivilege(void)
10 {
11 }
12 
13 BOOL JXAboutPrivilege::EnableShutdownPrivileges( VOID )
14 {
15     HANDLE hToken;
16     TOKEN_PRIVILEGES tkp;
17     BOOL Result = FALSE;
18 
19     if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
20         return FALSE;
21 
22     LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &(tkp.Privileges[0].Luid) );
23     tkp.PrivilegeCount = 1;
24     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
25 
26     AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, 0 );
27     DWORD dwError = GetLastError();
28     if ( ERROR_SUCCESS == dwError )
29         Result = TRUE;
30 
31     CloseHandle( hToken );
32     return Result;
33 }
34 
35 BOOL JXAboutPrivilege::EnableTermProcessPrivileges( VOID )
36 {
37     HANDLE hToken;
38     TOKEN_PRIVILEGES tkp;
39     BOOL Result = FALSE;
40 
41     if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
42         return FALSE;
43 
44     LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &(tkp.Privileges[0].Luid) );
45     tkp.PrivilegeCount = 1;
46     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
47 
48     AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, 0 );
49     DWORD dwError = GetLastError();
50     if ( ERROR_SUCCESS == dwError )
51         Result = TRUE;
52 
53     CloseHandle( hToken );
54     return Result;
55 }
56 
57 BOOL JXAboutPrivilege::EnableLoadDriverPrivileges( VOID )
58 {
59     HANDLE hToken;
60     TOKEN_PRIVILEGES tkp;
61     BOOL Result = FALSE;
62 
63     if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
64         return FALSE;
65 
66     LookupPrivilegeValue( NULL, SE_LOAD_DRIVER_NAME, &(tkp.Privileges[0].Luid) );
67     tkp.PrivilegeCount = 1;
68     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
69 
70     AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, 0 );
71     DWORD dwError = GetLastError();
72     if ( ERROR_SUCCESS == dwError )
73         Result = TRUE;
74 
75     CloseHandle( hToken );
76     return Result;
77 }
78 
79 BOOL JXAboutPrivilege::EnableDebugPrivilege(BOOL   fEnable)
80 {
81     BOOL   fOk   =   FALSE; //   Assume   function   fails
82     HANDLE   hToken;
83     //   Try   to   open   this   process‘s   access   token
84     if(OpenProcessToken(GetCurrentProcess(),   TOKEN_ADJUST_PRIVILEGES,   &hToken))
85     {
86         //   Attempt   to   modify   the   "Debug"   privilege
87         TOKEN_PRIVILEGES   tp;
88         tp.PrivilegeCount   =   1;
89         LookupPrivilegeValue(NULL,   SE_DEBUG_NAME,   &tp.Privileges[0].Luid);
90         tp.Privileges[0].Attributes   =   fEnable   ?   SE_PRIVILEGE_ENABLED   :   0;
91         AdjustTokenPrivileges(hToken,   FALSE,   &tp,   sizeof(tp),   NULL,   NULL);
92         fOk   =   (GetLastError()   ==   ERROR_SUCCESS);
93         CloseHandle(hToken);
94     }
95     return(fOk);
96 }
JXAboutPrivilege.cpp
技术分享
 1 #if !defined JX_Service_Control
 2 #define  JX_Service_Control
 3 #include <Windows.h>
 4 
 5 // Windows服务控制类
 6 class JXServiceControl
 7 {
 8 public:
 9     JXServiceControl(void);
10     ~JXServiceControl(void);
11 public:
12     int ChangeServicePath( );
13     int createService();
14     int deleteService();
15     void startService();
16     void stopService();
17     BOOL isSvsRuning();
18     BOOL isSvsExist();
19     //设置服务名
20     void SetServiceName(const char * str);
21     //设置服务管理面板显示名字
22     void SetServiceShowName(const char *str);
23     //设置服务EXE文件位置
24     void SetExePath(const char *str);
25 private:
26     //服务名
27     char sSname[MAX_PATH+1];
28     //服务Caption
29     char sShowName[MAX_PATH+1];
30     //服务可执行文件路径
31     char sSvcExePath[MAX_PATH+1];
32 };
33 
34 
35 
36 #endif
JXServiceControl.h
技术分享
  1 #include "StdAfx.h"
  2 #include "JXServiceControl.h"
  3 
  4 
  5 JXServiceControl::JXServiceControl(void)
  6 {
  7     memset(sSname,0,MAX_PATH);
  8     memset(sShowName,0,MAX_PATH);
  9     memset(sSvcExePath,0,MAX_PATH);
 10 }
 11 
 12 JXServiceControl::~JXServiceControl(void)
 13 {
 14 
 15 }
 16 
 17 int JXServiceControl::ChangeServicePath()
 18 {
 19     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
 20     SC_HANDLE hsev = NULL;
 21     if(scHandle != NULL)
 22     {
 23         hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
 24         if(hsev != NULL)
 25         {
 26             BOOL bRet = ChangeServiceConfig( 
 27                 hsev, 
 28                 SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,
 29                 SERVICE_AUTO_START,
 30                 SERVICE_ERROR_IGNORE,
 31                 sSvcExePath,
 32                 NULL,
 33                 NULL,
 34                 NULL,
 35                 NULL,
 36                 NULL,
 37                 sShowName
 38                 );
 39             CloseServiceHandle(hsev);
 40 
 41         }
 42         else 
 43         {
 44             CloseServiceHandle(scHandle);
 45             return 0;                
 46         }
 47         CloseServiceHandle(scHandle);
 48     }
 49     else    
 50         return -1;
 51 
 52     return 1;
 53 }
 54 
 55 int JXServiceControl::createService()
 56 {
 57     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);
 58     if (scHandle == NULL)
 59     {
 60         return -1;
 61     }
 62     SC_HANDLE hsvc = CreateService(scHandle,sSname,sShowName,SERVICE_ALL_ACCESS,
 63         SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,SERVICE_AUTO_START,
 64         SERVICE_ERROR_IGNORE,sSvcExePath,
 65         NULL,NULL,NULL,NULL,NULL);
 66     if (hsvc != NULL)
 67     {
 68         CloseServiceHandle(hsvc);
 69     }
 70     else
 71     {
 72         return 0;
 73     }
 74     CloseServiceHandle(scHandle);
 75     return 1;
 76 }
 77 
 78 int JXServiceControl::deleteService()
 79 {
 80     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
 81     SC_HANDLE hsev = NULL;
 82     if(scHandle != NULL)
 83     {
 84         hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
 85         SERVICE_STATUS mss;
 86         if(hsev != NULL)
 87         {
 88             QueryServiceStatus(hsev,&mss);
 89             if (mss.dwCurrentState != SERVICE_RUNNING)
 90             {
 91                 ControlService(hsev,SERVICE_CONTROL_STOP,&mss);
 92                 DeleteService(hsev);
 93 
 94             }
 95             CloseServiceHandle(hsev);
 96         } else 
 97         {
 98             CloseServiceHandle(scHandle);
 99             return 0;
100         }
101         CloseServiceHandle(scHandle);
102     }
103     else    return -1;
104     return 1;
105 }
106 
107 void JXServiceControl::stopService()
108 {
109     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
110     SC_HANDLE hsev = NULL;
111     if(scHandle != NULL)
112     {
113         hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
114         SERVICE_STATUS mss;
115         if(hsev != NULL)
116         {
117             QueryServiceStatus(hsev,&mss);
118             if (mss.dwCurrentState == SERVICE_RUNNING)
119             {
120                 ControlService(hsev,SERVICE_CONTROL_STOP,&mss);
121                 CloseServiceHandle(hsev);
122             }                
123         }
124         CloseServiceHandle(scHandle);
125     }
126 }
127 
128 BOOL JXServiceControl::isSvsRuning()
129 {
130     BOOL  ret = FALSE;
131     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
132     SC_HANDLE hsev = NULL;
133     if(scHandle != NULL)
134     {
135         hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
136         SERVICE_STATUS mss;
137         if(hsev != NULL)
138         {
139             QueryServiceStatus(hsev,&mss);
140             if (mss.dwCurrentState == SERVICE_RUNNING)
141             {
142                 ret = TRUE;
143                 CloseServiceHandle(hsev);
144             }
145 
146         }
147         CloseServiceHandle(scHandle);
148     }
149     return ret;
150 }
151 
152 BOOL JXServiceControl::isSvsExist()
153 {
154     BOOL ret = FALSE;
155     SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
156     SC_HANDLE hsev = NULL;
157     if(scHandle != NULL)
158     {
159         hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
160         DWORD err = GetLastError();
161         if (err == ERROR_SERVICE_DOES_NOT_EXIST)
162         {
163             ret = FALSE;
164         }
165         else
166         {
167             ret = TRUE;
168         }
169         if(hsev != NULL)
170         {
171             CloseServiceHandle(hsev);
172             CloseServiceHandle(scHandle);
173         }
174     }
175     return ret;
176 }
177 
178 void JXServiceControl::SetServiceName(const char * str)
179 {
180     strcpy_s(sSname,MAX_PATH,str);
181 }
182 
183 void JXServiceControl::SetServiceShowName(const char *str)
184 {
185     strcpy_s(sShowName,MAX_PATH,str);
186 }
187 
188 void JXServiceControl::SetExePath(const char *str)
189 {
190     strcpy_s(sSvcExePath,MAX_PATH,str);
191 }
JXServiceControl.cpp
技术分享
 1 #if !defined WINDOWS_SERVICE
 2 #define WINDOWS_SERVICE
 3 
 4 #include <Windows.h>
 5 #include <process.h>
 6 #include "JXAboutPrivilege.h"
 7 #include "JXServiceControl.h"
 8 
 9 // 服务名称 
10 #define SERVER_NAME ("WindowsService") 
11 
12 // 初始化Windows服务,参数为main函数的参数
13 int InitService(int argc, TCHAR* argv[]);
14 
15 // 安装Windows服务
16 void  InstallServices();
17 
18 // 卸载Windows服务
19 void UnInstallServices();
20 
21 // 运行服务
22 void Run();
23 
24 // 服务线程 需要外部实现
25 extern unsigned __stdcall SvcRun (void *Params );
26 
27 #endif
WindwosService.h
技术分享
  1 #include "WindwosService.h"
  2 
  3 
  4 SERVICE_STATUS ServiceStatus = {0};
  5 SERVICE_STATUS_HANDLE hStatus = NULL;
  6 
  7 void Run()
  8 {
  9     _beginthreadex(NULL, NULL, SvcRun, NULL, NULL, NULL);
 10 }
 11 
 12 void WINAPI ControlHandler(DWORD fdwControl)
 13 {
 14     switch(fdwControl)
 15     {
 16     case SERVICE_CONTROL_STOP:
 17     case SERVICE_CONTROL_SHUTDOWN:
 18         ServiceStatus.dwWin32ExitCode = 0;
 19         ServiceStatus.dwCurrentState = SERVICE_STOPPED;
 20     default: break;
 21     }
 22     SetServiceStatus(hStatus, &ServiceStatus);
 23 }
 24 
 25 void WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
 26 {
 27 
 28     ZeroMemory(&ServiceStatus, sizeof(ServiceStatus));
 29     ServiceStatus.dwServiceType = SERVICE_WIN32;
 30     ServiceStatus.dwCurrentState = SERVICE_START_PENDING;// 正在启动中... 
 31     ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
 32 
 33     hStatus = RegisterServiceCtrlHandler(SERVER_NAME, (LPHANDLER_FUNCTION)ControlHandler); // 注册当前服务的控制函数
 34     if (!hStatus)
 35     {
 36         OutputDebugString(" RegisterServiceCtrlHandler 失败....\n");
 37         return;
 38     }
 39     ServiceStatus.dwCurrentState = SERVICE_RUNNING;
 40     SetServiceStatus(hStatus, &ServiceStatus);// 修改服务状态
 41     //////////////////////下方为启动主线程/////////////////////////////////////////
 42     Run();
 43     //////////////////////////////////////////////////////////////////////////
 44     while(1)
 45     {
 46         ::Sleep(1000);
 47     }
 48     //::WaitForSingleObject(hThread,INFINITE); // 等待线程结束
 49     ServiceStatus.dwCurrentState = SERVICE_STOPPED;
 50     ServiceStatus.dwWin32ExitCode = -1;
 51     SetServiceStatus(hStatus, &ServiceStatus);
 52 }
 53 
 54 int InitService(int argc, TCHAR* argv[])
 55 {
 56     JXAboutPrivilege::EnableDebugPrivilege(TRUE);
 57     JXAboutPrivilege::EnableLoadDriverPrivileges();
 58     JXAboutPrivilege::EnableShutdownPrivileges();
 59     JXAboutPrivilege::EnableTermProcessPrivileges();
 60 
 61     if (argc == 2)
 62     {
 63         if (!stricmp(argv[1],("-install")))
 64         {
 65             // InstallServices();
 66             return 1;
 67         }
 68         if (!stricmp(argv[1], ("-uninstall")))
 69         {
 70             // UnInstallServices();
 71             return 1;
 72         }
 73         if (!stricmp(argv[1], ("-run")))
 74         {
 75             Run();
 76             while (TRUE)
 77                 Sleep(50);
 78             return 1;
 79         }
 80     }
 81         SERVICE_TABLE_ENTRY DispatchTable[] = { 
 82             { SERVER_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain }, 
 83             { NULL, NULL }
 84         };
 85 
 86         StartServiceCtrlDispatcher(DispatchTable);  
 87 }
 88 
 89 void InstallServices()
 90 {
 91     TCHAR path_nor[MAX_PATH] = { 0 };
 92     GetModuleFileName(NULL, path_nor, MAX_PATH);
 93 
 94     JXServiceControl sc;
 95     sc.SetExePath(path_nor);
 96     sc.SetServiceName((SERVER_NAME));
 97     sc.SetServiceShowName((SERVER_NAME));
 98 
 99 
100     if ( sc.isSvsExist() && sc.isSvsRuning()  )
101     {
102         sc.stopService();
103         sc.ChangeServicePath();
104     }
105     else if ( sc.isSvsExist() )
106     {
107         sc.ChangeServicePath();
108     }
109     else if (!sc.isSvsExist())
110     {
111         sc.createService();
112     }
113 
114     sc.startService();
115 }
116 
117 void UnInstallServices()
118 {
119     TCHAR path_nor[MAX_PATH] = { 0 };
120     GetModuleFileName(NULL, path_nor, MAX_PATH);
121 
122     JXServiceControl sc;
123     sc.SetExePath(path_nor);
124     sc.SetServiceName((SERVER_NAME));
125     sc.SetServiceShowName((SERVER_NAME));
126 
127 
128     if ( sc.isSvsExist() && sc.isSvsRuning() )
129     {
130         sc.stopService();
131     }
132     if( sc.isSvsExist() )
133         sc.deleteService();
134 }
WindwosService.cpp

 转载请注明出处....

VC Windows系统服务创建代码

标签:

原文地址:http://www.cnblogs.com/-jpp/p/5250120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!