代码之家  ›  专栏  ›  技术社区  ›  Frank

使用NamedPipe块读取文件,尽管使用重叠

  •  0
  • Frank  · 技术社区  · 7 年前

    pipeHandle = CreateFile(
                pipename,
                PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                0,
                nullptr,
                OPEN_EXISTING,
                0,
                nullptr);
    

    然后读取操作如下所示:

        OVERLAPPED overlapped;
            ZeroMemory(&overlapped, sizeof(OVERLAPPED));
            overlapped.hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
        successful = ReadFile(
                pipeHandle,
                buffer,
                4096 * sizeof(wchar_t),
                &numBytesRead,
                &overlapped
            );
        if (successful == FALSE)
        {
            LOG("Reading was not successful");
            if (GetLastError() != ERROR_IO_PENDING)
            {
                // The function call failed. ToDo: recovery.
                LOG_LAST_ERROR("Failed because of Error: ");
                return ERROR_READ_FAULT;
            }
            else
            {
                // TODO: add a timeout...
                successful = GetOverlappedResult(pipeHandle, &overlapped, &numBytesRead, TRUE);
            }
        }
        else
        {
            LOG("Reading was successful");
            // I/O completed:
            return ERROR_SUCCESS;
        }
    

    现在,我希望对ReadFile的调用会立即返回,这样我就可以处理可能的超时,但它会一直阻塞,直到调用返回。

    1 回复  |  直到 7 年前
        1
  •  1
  •   jlahd    7 年前

    在代码中 FILE_FLAG_OVERLAPPED dwDesiredAccess dwFlagsAndAttributes 参数

    pipeHandle = CreateFile(
            pipename,
            PIPE_ACCESS_DUPLEX,
            0,
            nullptr,
            OPEN_EXISTING,
            FILE_FLAG_OVERLAPPED,
            nullptr);