-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiskMonitor.cpp
More file actions
264 lines (235 loc) · 6.09 KB
/
DiskMonitor.cpp
File metadata and controls
264 lines (235 loc) · 6.09 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
#include "DeviceUtils.h"
#include "DiskMonitor.h"
#include <algorithm>
#include <cfgmgr32.h>
#include <devguid.h>
#include <fcntl.h>
#include <initguid.h>
#include <io.h>
#include <iostream>
#include <map>
#include <ntdddisk.h>
#include <SetupAPI.h>
#include <Shlwapi.h>
#include <vector>
#include <wchar.h>
#include <windows.h>
#include <winioctl.h>
using namespace std;
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "SetupApi.lib")
// 需过滤的系统目录
const vector<wstring> FILTER_PATHS = {
L"C:\\Users\\",
L"C:\\ProgramData\\",
L"C:\\Program Files (x86)\\",
L"C:\\Program Files\\",
};
DiskMonitor::~DiskMonitor() {
StopMonitoring();
// 关闭设备句柄
if (m_hDevice != INVALID_HANDLE_VALUE) {
CloseHandle(m_hDevice);
m_hDevice = INVALID_HANDLE_VALUE;
}
}
bool DiskMonitor::FromDeviceLetter(wchar_t driveLetter) {
wstring cDiskSymbol = (driveLetter + wstring(L":"));
UINT type = GetDriveType(cDiskSymbol.c_str());
if (type == DRIVE_CDROM || type == DRIVE_FIXED ||
type == DRIVE_REMOVABLE || type == DRIVE_REMOTE) {
TCHAR szBuf[MAX_PATH] = { 0 };
QueryDosDevice(cDiskSymbol.c_str(), szBuf, MAX_PATH);
m_volumePathName = cDiskSymbol + L'\\';
m_driveType = type;
m_deviceName = szBuf;
m_driveLetter = driveLetter;
return true;
}
m_volumePathName = L"";
m_driveType = 0;
m_deviceName = L"";
m_driveLetter = L'\0';
return false;
}
// 启动监控
bool DiskMonitor::StartMonitoring() {
lock_guard<mutex> lock(m_mutex);
if (m_isMonitoring) {
return true; // 已在监控中
}
m_hDir = CreateFileW(
DeviceUtils::RootPath(m_driveLetter).c_str(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
if (m_hDir == INVALID_HANDLE_VALUE) {
wprintf(L"打开目录失败,路径: %s,错误代码: %d\n", m_volumePathName.c_str(), GetLastError());
return false;
}
// 创建退出事件
m_hQuitEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!m_hQuitEvent) {
wprintf(L"创建退出事件失败,错误代码: %d\n", GetLastError());
CloseHandle(m_hDir);
m_hDir = INVALID_HANDLE_VALUE;
return false;
}
// 创建监控线程
m_hThread = CreateThread(NULL, 0, MonitorThread, this, 0, NULL);
if (!m_hThread) {
wprintf(L"创建监控线程失败,错误代码: %d\n", GetLastError());
CloseHandle(m_hQuitEvent);
CloseHandle(m_hDir);
m_hQuitEvent = NULL;
m_hDir = INVALID_HANDLE_VALUE;
return false;
}
m_isMonitoring = true;
wprintf(L"DiskMonitor: 设备 %s 开始监控\n", m_volumePathName.c_str());
return true;
}
// 停止监控
void DiskMonitor::StopMonitoring() {
do {
lock_guard<mutex> lock(m_mutex);
if (!m_isMonitoring) {
return; // 未在监控中
}
// 触发退出事件
if (m_hQuitEvent) {
SetEvent(m_hQuitEvent);
}
} while (0);
// 等待线程结束
if (m_hThread) {
WaitForSingleObject(m_hThread, 5000);
CloseHandle(m_hThread);
m_hThread = NULL;
}
do {
lock_guard<mutex> lock(m_mutex);
// 关闭资源
if (m_hQuitEvent) {
CloseHandle(m_hQuitEvent);
m_hQuitEvent = NULL;
}
if (m_hDir != INVALID_HANDLE_VALUE) {
CloseHandle(m_hDir);
m_hDir = INVALID_HANDLE_VALUE;
}
m_isMonitoring = false;
} while (0);
wprintf(L"设备 %s 停止监控\n", m_volumePathName.c_str());
}
// 监控线程(静态回调)
DWORD WINAPI DiskMonitor::MonitorThread(LPVOID lpParam) {
DiskMonitor* pThis = static_cast<DiskMonitor*>(lpParam);
if (pThis) {
return pThis->DoMonitor();
}
return 1;
}
// 实际监控逻辑
DWORD DiskMonitor::DoMonitor() {
OVERLAPPED overlapped = { 0 };
overlapped.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!overlapped.hEvent) {
return 1;
}
const DWORD bufferSize = 60 * 1024;
BYTE* pBuffer = new (nothrow) BYTE[bufferSize];
if (!pBuffer) {
CloseHandle(overlapped.hEvent);
return 1;
}
HANDLE hEvents[2] = { m_hQuitEvent, overlapped.hEvent };
while (true) {
DWORD bytesReturned = 0;
BOOL success = ReadDirectoryChangesW(
m_hDir,
pBuffer,
bufferSize,
TRUE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS |
FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY,
&bytesReturned,
&overlapped,
NULL
);
if (!success && GetLastError() != ERROR_IO_PENDING) {
Sleep(1000);
continue;
}
// 等待事件(退出或文件变化)
DWORD waitResult = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
if (waitResult == WAIT_OBJECT_0) {
break; // 退出事件触发
}
else if (waitResult == WAIT_OBJECT_0 + 1) {
// 处理文件变化通知
if (GetOverlappedResult(m_hDir, &overlapped, &bytesReturned, FALSE) && bytesReturned > 0) {
DWORD offset = 0;
while (offset < bytesReturned) {
PFILE_NOTIFY_INFORMATION pNotify = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(pBuffer + offset);
HandleFileNotify(pNotify);
if (pNotify->NextEntryOffset == 0) break;
offset += pNotify->NextEntryOffset;
}
}
ResetEvent(overlapped.hEvent);
}
else {
break; // 等待失败
}
}
// 清理资源
delete[] pBuffer;
CloseHandle(overlapped.hEvent);
return 0;
}
// 处理文件变化通知
void DiskMonitor::HandleFileNotify(PFILE_NOTIFY_INFORMATION pNotify) {
if (!pNotify) return;
// 解析文件名
wstring fileName;
fileName.resize(pNotify->FileNameLength / 2);
wmemcpy(&fileName[0], pNotify->FileName, fileName.size());
wstring fullPath = m_volumePathName + fileName;
// 过滤系统目录
bool skip = false;
for (const auto& filter : FILTER_PATHS) {
if (fullPath.substr(0, filter.size()) == filter) {
skip = true;
break;
}
}
if (skip) return;
// 打印事件信息
switch (pNotify->Action) {
case FILE_ACTION_ADDED:
wprintf(L"[新增] %s\n", fullPath.c_str());
break;
case FILE_ACTION_REMOVED:
wprintf(L"[删除] %s\n", fullPath.c_str());
break;
case FILE_ACTION_MODIFIED:
wprintf(L"[修改] %s\n", fullPath.c_str());
break;
case FILE_ACTION_RENAMED_OLD_NAME:
wprintf(L"[重命名-旧名] %s\n", fullPath.c_str());
break;
case FILE_ACTION_RENAMED_NEW_NAME:
wprintf(L"[重命名-新名] %s\n", fullPath.c_str());
break;
default:
wprintf(L"[未知操作(%d)] %s\n", pNotify->Action, fullPath.c_str());
break;
}
}