2015-10-22 131 views
0

代碼如下,它是線程的一部分。 pFileChange-> m_hDirectory類型爲HANDLE,如果類型爲CEvent,則爲pFileChange-> m_eventFileChange。 CreateFile和ReadDirectoryChangesW返回成功。我無法弄清楚爲什麼我得到一個無效的句柄狀態,請幫助!Waitformultipleobjects返回無效句柄

UINT CFileChange::FileMontiorThread(LPVOID pArgs) 
{ 
    CFileChange* pFileChange = NULL; 

    pFileChange = (CFileChange*)pArgs; 

    pFileChange = (CFileChange*)pArgs; 

    CString str = pFileChange->m_strDirectory; 

    LPSTR strDirectory; 
    strDirectory = str.GetBuffer(str.GetLength()); 
    PathRemoveFileSpec(strDirectory); 

    DWORD dwBytes = 0;  
    vector<BYTE> m_Buffer; 
    BOOL  m_bChildren; 
    OVERLAPPED m_Overlapped; 
    HANDLE arrHandles[2] = { pFileChange->m_hDirectory, pFileChange->m_eventFileChange }; 

    ::ZeroMemory(&m_Overlapped, sizeof(OVERLAPPED)); 
    DWORD dwBufferSize = 16384; 
    m_Buffer.resize(dwBufferSize); 
    m_bChildren = false; 


    pFileChange->m_hDirectory = ::CreateFile(
    (LPCSTR)(LPCTSTR)strDirectory, 
    FILE_LIST_DIRECTORY,     
    FILE_SHARE_READ      
    | FILE_SHARE_WRITE 
    | FILE_SHARE_DELETE, 
    NULL,        
    OPEN_EXISTING,      
    FILE_FLAG_BACKUP_SEMANTICS   
    | FILE_FLAG_OVERLAPPED, 
    NULL);        

    if (pFileChange->m_hDirectory == INVALID_HANDLE_VALUE) 
    { 
    return false; 
    } 

    BOOL success = ::ReadDirectoryChangesW(
    pFileChange->m_hDirectory, // handle to directory 
    &m_Buffer[0],      // read results buffer 
    m_Buffer.size(),     // length of buffer 
    m_bChildren,      // monitoring option 
    FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_FILE_NAME,  // filter conditions 
    &dwBytes,       // bytes returned 
    &m_Overlapped,      // overlapped buffer 
    NULL);   // no completion routine 

    DWORD dwWaitStatus; 

    while (!pFileChange->m_bKillThread) 
    { 
    dwWaitStatus = WaitForMultipleObjects(2, arrHandles, FALSE, INFINITE); 

    Switch(dwWaitStatus) 
    { 
    case WAIT_FAILED: 
     { 
      ULONG rc = 0; 
      rc = ::GetLastError(); 
      LPVOID lpMsgBuf = NULL; 
      ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 
       NULL, 
       rc, 
       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language 
       (LPTSTR)&lpMsgBuf, 
       0, 
       NULL); 
      CString strErrMsg; 
      strErrMsg.Format(_T("%s, %s, Reason:%s"), "", "",   (LPTSTR)lpMsgBuf); 
      break; 
     } 
    } 
    } 
    return 0; 
} 
+1

您很快就會將句柄複製到'arrHandles'中,* *它們在創建之前*。這當然不行。 –

+0

謝謝!它工作,我沒有注意到它。 – user2832424

回答

0

需要注意的是,因爲它規定了in the documentation,你不能在任何類型手柄等。

wait

等待一個目錄句柄是不會做你認爲它應該。 Read this related question及其答案以獲取更多信息和背景閱讀。

看起來你正在試圖創建一個文件夾監視器,或許read this blog post正確的方式來使用ReadDirectoryChangesW