forked from somma/_MyLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_tree.cpp
More file actions
510 lines (448 loc) · 11.1 KB
/
process_tree.cpp
File metadata and controls
510 lines (448 loc) · 11.1 KB
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
/**----------------------------------------------------------------------------
* process_tree.cpp
*-----------------------------------------------------------------------------
* module that manage running process
*-----------------------------------------------------------------------------
* All rights reserved by Noh,Yonghwan (fixbrain@gmail.com)
*-----------------------------------------------------------------------------
* 2014:6:15 22:23 created
**---------------------------------------------------------------------------*/
#include "stdafx.h"
#include "process_tree.h"
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool process::kill(_In_ DWORD exit_code)
{
_ASSERTE(true != _killed);
if (true == _killed) return true;
set_privilege(SE_DEBUG_NAME, TRUE);
HANDLE h = NULL;
do
{
h = OpenProcess(PROCESS_TERMINATE, FALSE, _pid);
if (NULL == h)
{
log_err
"OpenProcess() failed, pid = %u, gle = %u",
_pid,
GetLastError()
log_end
break;
}
if (!TerminateProcess(h, exit_code))
{
log_err
"TerminateProcess() failed, pid = %u, gle = %u",
_pid,
GetLastError()
log_end
break;
}
_killed = true;
log_dbg "pid = %u, %ws terminated", _pid, _process_name.c_str() log_end
} while (false);
if (NULL!=h)
{
CloseHandle(h); // TerminateProcess() is asynchronous, so must call CloseHandle()
}
set_privilege(SE_DEBUG_NAME, FALSE);
return (true == _killed) ? true : false;
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool
cprocess_tree::build_process_tree()
{
_proc_map.clear();
bool ret = false;
PROCESSENTRY32W proc_entry = {0};
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE)
{
log_err "CreateToolhelp32Snapshot() failed, gle = %u", GetLastError() log_end
return false;
}
if (true != set_privilege(SE_DEBUG_NAME, TRUE))
{
log_info "set_privilege(SE_DEBUG_NAME) failed." log_end
// just info
}
do
{
proc_entry.dwSize = sizeof(PROCESSENTRY32W);
if (!Process32First(snap, &proc_entry))
{
log_err "CreateToolhelp32Snapshot() failed, gle = %u", GetLastError() log_end
break;
}
do
{
FILETIME create_time={0};
HANDLE process_handle = OpenProcess(
PROCESS_QUERY_INFORMATION,
FALSE,
proc_entry.th32ProcessID
);
if(NULL == process_handle)
{
// too much logs.
//log_err
// "OpenProcess() failed, pid = %u, proc = %s, gle = %u",
// proc_entry.th32ProcessID,
// WcsToMbsEx(proc_entry.szExeFile).c_str(),
// GetLastError()
//log_end
// use create time 0!
}
else
{
FILETIME dummy_time;
if (!GetProcessTimes(process_handle, &create_time, &dummy_time, &dummy_time, &dummy_time))
{
log_err "GetProcessTimes() failed, gle = %u", GetLastError() log_end
// use create time 0!
}
CloseHandle(process_handle); process_handle = NULL;
}
add_process(proc_entry.th32ParentProcessID, proc_entry.th32ProcessID, create_time, proc_entry.szExeFile);
} while (Process32Next(snap, &proc_entry));
} while (false);
CloseHandle(snap);
set_privilege(SE_DEBUG_NAME, FALSE);
return true;
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
DWORD cprocess_tree::find_process(_In_ const wchar_t* process_name)
{
_ASSERTE(NULL != process_name);
if (NULL == process_name) return false;
process_map::iterator it = _proc_map.begin();
process_map::iterator ite = _proc_map.end();
for(; it != ite; ++it)
{
if (0 == it->second.process_name().compare(process_name))
{
// found
return it->second.pid();
}
}
return 0;
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
const wchar_t* cprocess_tree::get_process_name(_In_ DWORD pid)
{
process_map::iterator it = _proc_map.find(pid);
if (it == _proc_map.end()) return NULL;
return it->second.process_name().c_str();
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
DWORD cprocess_tree::get_parent_pid(_In_ DWORD child_pid)
{
process_map::iterator it = _proc_map.find(child_pid);
if (it == _proc_map.end()) return 0;
process prcs = it->second;
return prcs.ppid();
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
const wchar_t* cprocess_tree::get_parent_name(_In_ DWORD child_pid)
{
DWORD ppid = get_parent_pid(child_pid);
if (0 == ppid) return NULL;
process_map::iterator it = _proc_map.find(ppid);
if (it == _proc_map.end()) return NULL;
return it->second.process_name().c_str();
}
/**
* @brief 모든 프로세스를 콜백 함수를 통해 열거한다.
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::iterate_process(_In_ fnproc_tree_callback callback, _In_ DWORD_PTR callback_tag)
{
_ASSERTE(NULL != callback);
if (NULL == callback) return;
process_map::iterator its = _proc_map.begin();
process_map::iterator ite= _proc_map.end();
for(; its != ite; ++its)
{
if (true != callback(its->second, callback_tag)) break;
}
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::iterate_process_tree(_In_ DWORD root_pid, _In_ fnproc_tree_callback callback, _In_ DWORD_PTR callback_tag)
{
_ASSERTE(NULL != callback);
if (NULL == callback) return;
process_map::iterator it = _proc_map.find(root_pid);
if (it == _proc_map.end()) return;
process root = it->second;
iterate_process_tree(root, callback, callback_tag);
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::print_process_tree(_In_ DWORD root_pid)
{
process_map::iterator it = _proc_map.find(root_pid);
if (it != _proc_map.end())
{
DWORD depth = 0;
print_process_tree(it->second, depth);
_ASSERTE(0 == depth);
}
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::print_process_tree(_In_ const wchar_t* root_process_name)
{
_ASSERTE(NULL != root_process_name);
if (NULL == root_process_name) { return; }
DWORD pid = find_process(root_process_name);
if (0 != pid)
{
print_process_tree(pid);
}
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool cprocess_tree::kill_process(_In_ DWORD pid)
{
if (pid == 0 || pid == 4) return false;
process_map::iterator it = _proc_map.find(pid);
if (it == _proc_map.end()) return true;
process prcs = it->second;
return prcs.kill(0);
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool cprocess_tree::kill_process(_In_ const wchar_t* process_name)
{
_ASSERTE(NULL != process_name);
if (NULL == process_name) return false;
DWORD pid = find_process(process_name);
return kill_process(pid);
}
/**
* @brief root_pid 와 그 자식 프로세스를 모두 종료한다.
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool cprocess_tree::kill_process_tree(_In_ DWORD root_pid)
{
if (root_pid == 0 || root_pid == 4) return false;
process_map::iterator it = _proc_map.find(root_pid);
if (it == _proc_map.end()) return true;
process root = it->second;
// check process is already killed.
if (true == root.killed())
{
log_info "already killed. pid = %u, %ws", root.pid(), root.process_name().c_str() log_end
return true;
}
// kill process tree include root.
kill_process_tree(root);
return true;
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void
cprocess_tree::add_process(
_In_ DWORD ppid,
_In_ DWORD pid,
_In_ FILETIME& creation_time,
_In_ const wchar_t* process_name
)
{
process p(process_name, ppid, pid, *(uint64_t*)&creation_time, false);
_proc_map.insert( std::make_pair(pid, p) );
}
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::print_process_tree(_In_ process& p, _In_ DWORD& depth)
{
std::wstringstream prefix;
for(DWORD i = 0; i < depth; ++i)
{
prefix << " ";
}
log_info
"%spid = %u (ppid = %u), %ws ", prefix.str().c_str(),
p.pid(),
p.ppid(),
p.process_name().c_str()
log_end
// p._pid 를 ppid 로 갖는 item 을 찾자
process_map::iterator it = _proc_map.begin();
process_map::iterator ite= _proc_map.end();
for(; it != ite; ++it)
{
// ppid 의 값은 동일하지만 ppid 프로세스는 이미 종료되고, 새로운 프로세스가 생성되고, ppid 를 할당받은 경우가
// 발생할 수 있다. 따라서 ppid 값이 동일한 경우 ppid 를 가진 프로세스의 생성 시간이 pid 의 생성시간 값이 더 커야 한다.
if ( it->second.ppid() == p.pid() &&
(uint64_t)it->second.creation_time() > (uint64_t)p.creation_time())
{
print_process_tree(it->second, ++depth);
--depth;
}
}
}
/**
* @brief 자식의 자식의 자식까지... 재귀적으로 죽이고, 나도 죽는다. :-)
중간에 권한 문제라든지 뭔가 문제가 있는 프로세스가 있을 수도 있다.
못죽이는 놈은 냅두고, 죽일 수 있는 놈은 다 죽이려고, 리턴값을 void 로 했음
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::kill_process_tree(_In_ process& root)
{
// terminate child processes first if exists.
process_map::iterator its = _proc_map.begin();
process_map::iterator ite= _proc_map.end();
for(; its != ite; ++its)
{
// ppid 의 값은 동일하지만 ppid 프로세스는 이미 종료되고, 새로운 프로세스가 생성되고, ppid 를 할당받은 경우가
// 발생할 수 있다. 따라서 ppid 값이 동일한 경우 ppid 를 가진 프로세스의 생성 시간이 pid 의 생성시간 값이 더 커야 한다.
if ( its->second.ppid() == root.pid() &&
its->second.creation_time() > root.creation_time())
{
kill_process_tree(its->second);
}
}
// terminate parent process
root.kill(0);
}
/**
* @brief process map 을 순회하면서 콜백함수를 호출한다.
콜백함수가 false 를 리턴하면 순회를 즉시 멈춘다.
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
void cprocess_tree::iterate_process_tree(_In_ process& root, _In_ fnproc_tree_callback callback, _In_ DWORD_PTR callback_tag)
{
// parent first
if (true != callback(root, callback_tag)) return;
// childs
process_map::iterator its = _proc_map.begin();
process_map::iterator ite= _proc_map.end();
for(; its != ite; ++its)
{
// ppid 의 값은 동일하지만 ppid 프로세스는 이미 종료되고, 새로운 프로세스가 생성되고, ppid 를 할당받은 경우가
// 발생할 수 있다. 따라서 ppid 값이 동일한 경우 ppid 를 가진 프로세스의 생성 시간이 pid 의 생성시간 값이 더 커야 한다.
if ( its->second.ppid() == root.pid() &&
its->second.creation_time() > root.creation_time())
{
iterate_process_tree(its->second, callback, callback_tag);
}
}
}