我正在异步调用ReadDirectoryChangesW来监视后台线程中的目录更改。

这将打开目录(basePath)并启动“读取”线程的方式:

    m_hDIR = CreateFileW(
            basePath,
            FILE_LIST_DIRECTORY | GENERIC_READ,
            FILE_SHARE_WRITE | FILE_SHARE_READ,
            NULL,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
            NULL);

        if (m_hDIR == INVALID_HANDLE_VALUE)
            throw CrException(CrWin32ErrorString());

        //Start reading changes in background thread
        m_Callback = std::move(a_Callback);
        m_Reading = true;
        m_ReadThread = std::thread(&CrDirectoryWatcher::StartRead, this);


这是StartRead() :(注意:m_Readingatomic<bool>

void StartRead()
        {
            DWORD dwBytes = 0;
            FILE_NOTIFY_INFORMATION fni{0};
            OVERLAPPED o{0};

            //Be sure to set the hEvent member of the OVERLAPPED structure to a unique event.
            o.hEvent = CreateEvent(0, 0, 0, 0);

            while(m_Reading)
            {
                if (!ReadDirectoryChangesW(m_hDIR,
                    &fni, sizeof(fni),
                    TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,
                    &dwBytes, &o, NULL))
                {
                    CrAssert(0, CrWin32ErrorString());
                }

                if (!GetOverlappedResult(m_hDIR, &o, &dwBytes, FALSE))
                    CrAssert(0, CrWin32ErrorString());

                if (fni.Action != 0)
                {
                    std::wstring fileName(fni.FileName, fni.FileNameLength);
                    m_Callback(fileName);
                    fni.Action = 0;
                }
            }
        }


基本上,我正在“轮询”每帧的新更改。
现在,当我调用GetOverlappedResult()时,它将失败并产生以下错误:


  重叠的I / O事件未处于信号状态。


我想念什么吗?是ReadDirectoryChangesW被称为每个“刻度”吗?还是只是在检测到新变化时?

注意:当我省略OVERLAPPED结构(和GetOverlappedResult)时,它可以工作,但是会阻塞线程,直到读取更改为止。这会阻止我的应用程序正确终止。 (即我无法加入该线程)

最佳答案

调用GetOverlappedResult()时,如果将bWait参数设置为FALSE并且I / O操作尚未完成,则GetOverlappedResult()失败,并显示ERROR_IO_INCOMPLETE错误代码:


  b等待[输入]
  如果此参数为TRUE,并且Internal结构的lpOverlapped成员为STATUS_PENDING,则该函数在操作完成之前不会返回。如果此参数为FALSE并且操作仍在进行中,则函数返回FALSE,而GetLastError函数返回ERROR_IO_INCOMPLETE


那不是致命的错误,因此只需忽略该错误并继续。

是的,请确保在ReadDirectoryChangesW()报告上一个I / O操作首先完成之前,不要再次调用GetOverlappedResult()

如此说来,您的代码还有另一个问题。您的线程在堆栈上分配了一个FILE_NOTIFY_INFORMATION实例。如果查看FILE_NOTIFY_INFORMATION的定义,则其FileName字段是可变长度的:

typedef struct _FILE_NOTIFY_INFORMATION {
  DWORD NextEntryOffset;
  DWORD Action;
  DWORD FileNameLength;
  WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;



  文档名称
  可变长度字段,包含相对于目录句柄的文件名。文件名采用Unicode字符格式,并且不以null结尾。


这意味着静态分配FILE_NOTIFY_INFORMATION将会太小,并且dwBytes几乎总是为0,因为ReadDirectoryChangesW()无法将完整的FILE_NOTIFY_INFORMATION返回给您(除非FileName恰好是长度为1个字符):


  首次调用ReadDirectoryChangesW时,系统会分配一个缓冲区来存储更改信息。该缓冲区与目录句柄相关联,直到它被关闭并且其大小在其生命周期内保持不变。在两次调用此函数之间发生的目录更改将添加到缓冲区中,然后在下一次调用时返回。如果缓冲区溢出,则将丢弃缓冲区的全部内容,lpBytesReturned参数包含零,并且ReadDirectoryChangesW函数将失败,错误代码为ERROR_NOTIFY_ENUM_DIR





  ERROR_NOTIFY_ENUM_DIR
  1022(0x3FE)
  通知更改请求正在完成,并且信息没有在调用者的缓冲区中返回。现在,调用者需要枚举文件以查找更改。


因此,您需要动态分配一个大字节缓冲区以接收FILE_NOTIFY_INFORMATION数据,然后只要GetOverlappedResult()报告数据可用,就可以遍历该缓冲区。

您的线程应该看起来像这样:

void StartRead()
{
    DWORD dwBytes = 0;
    std::vector<BYTE> buffer(1024*64);
    OVERLAPPED o{0};
    bool bPending = false;

    //Be sure to set the hEvent member of the OVERLAPPED structure to a unique event.
    o.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!o.hEvent) {
        CrAssert(0, CrWin32ErrorString());
    }

    while (m_Reading)
    {
        bPending = ReadDirectoryChangesW(m_hDIR,
            &buffer[0], buffer.size(),
            TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,
            &dwBytes, &o, NULL);
        if (!bPending)
        {
            CrAssert(0, CrWin32ErrorString());
        }

        while (m_Reading)
        {
            if (GetOverlappedResult(m_hDIR, &o, &dwBytes, FALSE))
            {
                bPending = false;

                if (dwBytes != 0)
                {
                    FILE_NOTIFY_INFORMATION *fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(&buffer[0]);
                    do
                    {
                        if (fni->Action != 0)
                        {
                            std::wstring fileName(fni->FileName, fni->FileNameLength);
                            m_Callback(fileName);
                        }

                        if (fni->NextEntryOffset == 0)
                            break;

                        fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(reinterpret_cast<BYTE*>(fni) + fni->NextEntryOffset);
                    }
                    while (true);
                }

                break;
            }

            if (GetLastError() != ERROR_IO_INCOMPLETE) {
                CrAssert(0, CrWin32ErrorString());
            }

            Sleep(10);
        }

        if (bPending)
        {
            CancelIo(m_hDIR);
            GetOverlappedResult(m_hDIR, &o, &dwBytes, TRUE);
        }
    }

    CloseHandle(o.hEvent);
}


另一种无需定期轮询I / O状态即可实现此目的的方法是摆脱m_Reading并使用等待事件。让操作系统在应调用GetOverlappedResult()或终止时向线程发出信号,以使其可以在不忙于做某事的其余时间中休眠:

m_hDIR = CreateFileW(
            basePath,
            FILE_LIST_DIRECTORY | GENERIC_READ,
            FILE_SHARE_WRITE | FILE_SHARE_READ,
            NULL,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
            NULL);

if (m_hDIR == INVALID_HANDLE_VALUE)
    throw CrException(CrWin32ErrorString());

m_TermEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!m_TermEvent)
    throw CrException(CrWin32ErrorString());

//Start reading changes in background thread
m_Callback = std::move(a_Callback);
m_ReadThread = std::thread(&CrDirectoryWatcher::StartRead, this);

...

SetEvent(m_TermEvent);
m_ReadThread.join();




void StartRead()
{
    DWORD dwBytes = 0;
    std::vector<BYTE> buffer(1024*64);
    OVERLAPPED o{0};
    bool bPending = false, bKeepRunning = true;

    //Be sure to set the hEvent member of the OVERLAPPED structure to a unique event.
    o.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!o.hEvent) {
        CrAssert(0, CrWin32ErrorString());
    }

    HANDLE h[2] = {o.hEvent, h_TermEvent};

    do
    {
        bPending = ReadDirectoryChangesW(m_hDIR,
            &buffer[0], buffer.size(),
            TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,
            &dwBytes, &o, NULL);
        if (!bPending)
        {
            CrAssert(0, CrWin32ErrorString());
        }

        switch (WaitForMultipleObjects(2, h, FALSE, INFINITE))
        {
            case WAIT_OBJECT_0:
            {
                if (!GetOverlappedResult(m_hDIR, &o, &dwBytes, TRUE)) {
                    CrAssert(0, CrWin32ErrorString());
                }

                bPending = false;

                if (dwBytes == 0)
                    break;

                FILE_NOTIFY_INFORMATION *fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(&buffer[0]);
                do
                {
                    if (fni->Action != 0)
                    {
                        std::wstring fileName(fni->FileName, fni->FileNameLength);
                        m_Callback(fileName);
                    }

                    if (fni->NextEntryOffset == 0)
                         break;

                    fni = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(reinterpret_cast<BYTE*>(fni) + fni->NextEntryOffset);
                }
                while (true);

                break;
            }

            case WAIT_OBJECT_0+1:
                bKeepRunning = false;
                break;

            case WAIT_FAILED:
                CrAssert(0, CrWin32ErrorString());
                break;
        }
    }
    while (bKeepRunning);

    if (bPending)
    {
        CancelIo(m_hDIR);
        GetOverlappedResult(m_hDIR, &o, &dwBytes, TRUE);
    }

    CloseHandle(o.hEvent);
}

关于c++ - ReadDirectoryChangesW和GetOverlappedResult,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43664998/

10-13 09:16