2015-10-22 91 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