window服务编程

window下编写服务程序样例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#pragma once
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <tchar.h>
#include <comutil.h>

#define SLEEP_TIME 5000
#define LOGFILE "d:\\ITXBaseProviderService.txt"

using namespace std;
char * ServiceName="ITXBaseProviderService";

enum EnumRunState
{
None=0,
Running=1,
Stoped=2,
Pause=3,
};

EnumRunState RunState;

int WriteToLog(char* str)
{
FILE* log;
log=fopen(LOGFILE,"a+");
if(log==NULL) return 0;
fprintf(log,"%s\n",str);
fclose(log);
return 1;
}

//定义变量和方法
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
HANDLE terminateEvent; //事件
HANDLE threadHandle; //线程

VOID terminate(DWORD error);
void ServiceMain(int argc,char** argv);
void ControlHandler(DWORD request);
int InitService();
//
BOOL RunService(char * sSvcName);
VOID ResumeService();
VOID PauseService();
VOID StopService();
//
BOOL SendStatusToSCM (DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwServiceSpecificExitCode,
DWORD dwCheckPoint,
DWORD dwWaitHint);
//
void InstallService();
void UninstallService();
//
DWORD WINAPI ServiceThread(LPDWORD param);

//安装入口点
void main(int argc, char* argv[])
{
SERVICE_TABLE_ENTRY ServiceTable[2];
//设置服务名称和服务入口函数
ServiceTable[0].lpServiceName = ServiceName;
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;

//引数
if(argc<=1)
{
cout<<"使用方法:"<<endl;
cout<<"\"install\"";
cout<<"or";
cout<<"\"uninstall\"";
cout<<"\"exec \"";
cout<<" parameter required in the command line"<<endl;
}
if(argc>1)
{
if(_stricmp("install",argv[1])==0)
{ //install(InstallService)
InstallService();
cout<<"installService Succed!"<<endl;
}
else if(_stricmp("uninstall",argv[1])==0)
{ //uninstall(UninstallService)
UninstallService();
cout<<"UninstallService Succed!"<<endl;
}
else if(_stricmp("exec",argv[1])==0)
{ //exec(ServiceMain)
RunService(ServiceName);
}
else
{ //usage(使用方法)表示
cout<<"使用方法 :"<<endl;
//"install"
cout<<"\"install\"";
//"or"
cout<<"or";
//"uninstall"
cout<<"\"uninstall\"";
//"exec"
cout<<"\"exec \"";
//"or"
cout<<"or";
cout<<" parameter required in the command line"<<endl;
}
}
//-------------------------------------------------
//启动服务的控制分派机线程(启动并执行一个新线程)
StartServiceCtrlDispatcher(ServiceTable);
}


//服务入口点(主线程)
void ServiceMain(int argc,char** argv)
{
int success;
//开始服务
RunService(ServiceName);

//注册服务控制处理函数
hStatus = RegisterServiceCtrlHandler(ServiceName,(LPHANDLER_FUNCTION)ControlHandler);
if(!hStatus)
{
WriteToLog("ServiceMain函数中注册服务控制处理函数失败!\n");
return;
}
//向SCM报告工作状态
RunState=EnumRunState::Running;
ServiceStatus.dwCurrentState=SERVICE_RUNNING;
ServiceStatus.dwServiceType=SERVICE_WIN32;
ServiceStatus.dwControlsAccepted =
SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN;
/*SetServiceStatus(hStatus,&ServiceStatus);*/

////启动工作循环(这个模块在另外一个线程中执行)
//while(RunState==EnumRunState::Running)
//{
// WriteToLog("ServiceMain函数写日志\n");
// Sleep(500);
//}
//创建一个终结事件
terminateEvent = CreateEvent (0,TRUE,FALSE,0);
if (!terminateEvent)
{
terminate(GetLastError());
return;
}
//
success = SendStatusToSCM(SERVICE_START_PENDING,NO_ERROR,0,2,1000);
if (!success)
{
terminate(GetLastError());
return;
}
//初始化
success = InitService();
if (!success)
{
terminate(GetLastError());
return;
}

success = SendStatusToSCM(SERVICE_RUNNING,NO_ERROR,0,0,0);
if (!success)
{
terminate(GetLastError());
return;
}

//等待停止
WaitForSingleObject ( terminateEvent, INFINITE);

terminate(0);
WriteToLog("ServiceMain函数执行完毕!");
}

//服务控制台命令处理函数
void ControlHandler(DWORD request)
{
DWORD currentState = 0;
BOOL success;
WriteToLog("ControlHandler:"+request);
switch(request)
{
case SERVICE_CONTROL_STOP:
RunState=EnumRunState::Stoped;
currentState = SERVICE_STOP_PENDING;
ServiceStatus.dwCurrentState=currentState;
SetServiceStatus(hStatus,&ServiceStatus);
StopService();
return;
case SERVICE_CONTROL_PAUSE:
RunState=EnumRunState::Pause;
currentState = SERVICE_PAUSED;
ServiceStatus.dwCurrentState=currentState;
SetServiceStatus(hStatus,&ServiceStatus);
PauseService();
break;
case SERVICE_CONTROL_CONTINUE:
RunState=EnumRunState::Running;
currentState = SERVICE_RUNNING;
ServiceStatus.dwCurrentState=currentState;
SetServiceStatus(hStatus,&ServiceStatus);
ResumeService();
break;
case SERVICE_CONTROL_INTERROGATE:
// it will fall to bottom and send status
break;

// Do nothing in a shutdown. Could do cleanup
// here but it must be very quick.
case SERVICE_CONTROL_SHUTDOWN:
// Do nothing on shutdown
return;
default:
break;
}
//ServiceStatus.dwCurrentState=currentState;
//SetServiceStatus(hStatus,&ServiceStatus);
}

//初始化服务(开始服务时执行)
int InitService()
{
int result;
//写日志信息
result=WriteToLog("Monitoring started.");
//开始一个线程 Start the service's thread
DWORD id;
threadHandle = CreateThread(0, 0,(LPTHREAD_START_ROUTINE)ServiceThread,0, 0, &id);
if (threadHandle==0)
{
result=0;
}
else
{
result=1;
}
//
WriteToLog("InitService一个线程开始了!");
return result;
}

DWORD WINAPI ServiceThread(LPDWORD param)
{
//线程操作
while(RunState==EnumRunState::Running)
{
WriteToLog("线程中写日志\n");
Sleep(500);
}
WriteToLog("线程操作ServiceThread完成!");
return 0;
}

//
BOOL RunService(char * sSvcName)
{
SC_HANDLE schSCManager;
SC_HANDLE scHandle;
BOOL boolRet;

// open to SCM
schSCManager = OpenSCManager(
0,
0,
SC_MANAGER_ALL_ACCESS
);

//Open
scHandle = OpenService(
schSCManager,
sSvcName,
SERVICE_ALL_ACCESS
);

//start
boolRet = StartService(
scHandle,
0,
NULL);

return boolRet;
}


VOID ResumeService()
{
//pauseService=FALSE;
//ResumeThread(threadHandle);
return;
}
VOID PauseService()
{
//pauseService = TRUE;
//SuspendThread(threadHandle);
return;
}
VOID StopService()
{
RunState=EnumRunState::Stoped;//=FALSE;
// Set the event that is holding ServiceMain
// so that ServiceMain can return
SetEvent(terminateEvent);
}
//安装/反安装函数
void InstallService()
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
char szPath[512];
string userName = "NT AUTHORITY\\NetworkService";

//Install Starting...
//获取模块文件路径名称
if(!GetModuleFileName(NULL,szPath,512))
{
return;
}

// open to SCM 
schSCManager = OpenSCManager(
0, // pointer to machine name string
0, // pointer to database name string
SC_MANAGER_CREATE_SERVICE // type of access
);
if (!schSCManager)
{
WriteToLog("OpenScManagerErrorID:" + GetLastError());
return;
}
// Install 新服务
schService = CreateService(
schSCManager, // handle to service control manager database
ServiceName, // pointer to name of service to start
ServiceName, // pointer to display name
SERVICE_ALL_ACCESS,// type of access to service
SERVICE_WIN32_OWN_PROCESS,// type of service
SERVICE_DEMAND_START,// when to start service
SERVICE_ERROR_NORMAL,// severity if service fails to start
szPath, // pointer to name of binary file
NULL, // pointer to name of load ordering group
NULL, // pointer to variable to get tag identifier
NULL, // pointer to array of dependency names
userName.c_str(), // pointer to account name of service
NULL // pointer to password for service account
);

if (!schService)
{
WriteToLog("CreateServiceErrorID:"+GetLastError());
return;
}
else
{
WriteToLog("Service installed\n");
}

CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
WriteToLog("Install Ending...\n");
}

void UninstallService()
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
BOOL success;
SERVICE_STATUS svcStatus;

WriteToLog("Uninstall Starting...");

// open to SCM 
schSCManager = OpenSCManager(
0,// pointer to machine name string
0,// pointer to database name string
SC_MANAGER_CREATE_SERVICE // type of access
);
if (!schSCManager)
{
WriteToLog("OpenScManagerErrorID:"+GetLastError());
return;
}

//打开一个服务
schService = OpenService(
schSCManager, // handle to service control manager database
ServiceName, // pointer to name of service to start
SERVICE_ALL_ACCESS | DELETE// type of access to service
);
if (!schService)
{
WriteToLog("OpenServiceErrorID:"+GetLastError());
return;
}
//(if necessary)
success = QueryServiceStatus(schService, &svcStatus);
if (!success)
{
WriteToLog("In QueryServiceStatus ErrorID:"+GetLastError());
return;
}
if (svcStatus.dwCurrentState != SERVICE_STOPPED)
{
WriteToLog("Stopping service...");
success = ControlService(
schService, // handle to service
SERVICE_CONTROL_STOP, // control code
&svcStatus // pointer to service status structure
);
if (!success)
{
WriteToLog("In ControlServiceErrorID:"+GetLastError());
return;
}
}

//等待
do
{
QueryServiceStatus(schService,&svcStatus);
Sleep(500);

}while(SERVICE_STOP_PENDING==svcStatus.dwCurrentState);

if(SERVICE_STOPPED!=svcStatus.dwCurrentState)
{
WriteToLog("Failed to Stop Service ErrorID:"+GetLastError());
return;
}

//删除服务
success = DeleteService(schService);
if (success)
{
WriteToLog("Service removed\n");
}
else
{
WriteToLog("In DeleteService ErrorID:"+GetLastError());
return;
}
//Clean up
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
WriteToLog("Uninstal Ending...");
}

//
BOOL SendStatusToSCM (DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwServiceSpecificExitCode,
DWORD dwCheckPoint,
DWORD dwWaitHint)
{
BOOL success;
SERVICE_STATUS serviceStatus;

// Fill in all of the SERVICE_STATUS fields
serviceStatus.dwServiceType =SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwCurrentState = dwCurrentState;

// If in the process of something, then accept
// no control events, else accept anything
if (dwCurrentState == SERVICE_START_PENDING)
serviceStatus.dwControlsAccepted = 0;
else
serviceStatus.dwControlsAccepted =
SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN;

// if a specific exit code is defines, set up
// the win32 exit code properly
if (dwServiceSpecificExitCode == 0)
serviceStatus.dwWin32ExitCode =dwWin32ExitCode;
else
serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
serviceStatus.dwServiceSpecificExitCode =dwServiceSpecificExitCode;

serviceStatus.dwCheckPoint = dwCheckPoint;
serviceStatus.dwWaitHint = dwWaitHint;

// Pass the status record to the SCM
//SERVICE_STATUS_HANDLE serviceStatusHandle;
success = SetServiceStatus (hStatus,&serviceStatus);
if (!success)
{
StopService();
}
return success;
}
//
VOID terminate(DWORD error)
{
// if terminateEvent has been created, close it.
if (terminateEvent)
CloseHandle(terminateEvent);

// Send a message to the scm to tell about
// stop age
if (hStatus)
SendStatusToSCM(SERVICE_STOPPED, error,
0, 0, 0);

// If the thread has started kill it off
if (threadHandle)
CloseHandle(threadHandle);

// Do not need to close serviceStatusHandle
}


文章目录