#include #include #include #include #include void WatchDirectory(int); HANDLE *dwChangeHandles = NULL; HANDLE *dwThreads = NULL; DWORD WINAPI ThreadProc(LPVOID); DWORD WINAPI ThreadProc(LPVOID lpParam) { int index = (int)lpParam; WatchDirectory(index); return 0; } void _tmain(int argc, TCHAR *argv[]) { int how_many = 50; int i; DWORD status; DWORD dwThreadID; if(argc < 2) { _tprintf(TEXT("Usage: %s [number]\n"), argv[0]); _tprintf(TEXT(" Where number * 64 change notifications will be created and monitored for the same folder .\n")); return; } if (argc > 2) how_many = _tstoi(argv[2]); if (how_many <= 0) how_many = 100; _tprintf(TEXT("Monitoring %s - %d change notifications.\n"), argv[1], how_many * 64); dwChangeHandles = (HANDLE *)calloc(how_many * 64, sizeof(HANDLE)); dwThreads = (HANDLE *)calloc(how_many, sizeof(HANDLE)); for (i = 0; i < how_many * 64; i++) { dwChangeHandles[i] = FindFirstChangeNotification( argv[1], // directory to watch FALSE, // do not watch subtree 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); if (dwChangeHandles[i] == INVALID_HANDLE_VALUE || dwChangeHandles[i] == NULL) { status = GetLastError(); _tprintf(TEXT("ERROR: FindFirstChangeNotification failed. Error code %lu.\n"), status); ExitProcess(status); } } for (i = 0; i < how_many; i++) { dwThreads[i] = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE)ThreadProc, (LPVOID)i, // no thread function arguments 0, // default creation flags &dwThreadID); // receive thread identifier } status = WaitForMultipleObjects(how_many, dwThreads, TRUE, INFINITE); for (i = 0; i < how_many * 64; i++) { FindCloseChangeNotification(dwChangeHandles[i]); } free((void*)dwChangeHandles); free((void*)dwThreads); ExitProcess(0); } void WatchDirectory(int index) { DWORD dwWaitStatus; int idx; DWORD status; DWORD dwTotal = 0; int i; BOOL bWaitAll = false; while (TRUE) { dwWaitStatus = WaitForMultipleObjects(64, &dwChangeHandles[index * 64], bWaitAll, INFINITE); if (dwWaitStatus == WAIT_FAILED || (dwWaitStatus >= (WAIT_OBJECT_0 + 64))) { _tprintf(TEXT("ERROR: [%d] WaitForMultipleObjects returned %lu.\n"), index, dwWaitStatus); return; } idx = dwWaitStatus - WAIT_OBJECT_0; dwTotal++; //_tprintf(TEXT("Thread %04d - CNH %d idx %d total %lu\n"), index, index * 64 + idx, idx, dwTotal); if (FindNextChangeNotification(dwChangeHandles[index * 64 + idx]) == FALSE) { status = GetLastError(); _tprintf(TEXT("ERROR: [%d] FindNextChangeNotification function failed. Error code %lu\n"), index, status); return; } } }