通过重叠IO异步命名Windows管道通信

时间:2017-03-24 13:12:47

标签: c windows pipe client-server ipc

我正在使用重叠IO来同时读取和编写C代码中的单个Windows管道。我想编写一个同步函数来从单独的线程读取和写入数据。如果您使用的是同步IO,则无法同时读取和写入管道。我的客户端和我的服务器使用相同的写/读功能。我的客户端一次又一次地发送服务器从未接收过的数据。有谁知道这会怎么样?如果我在客户端使用同步IO,一切都按预期工作。

服务器管道由以下cmd打开:

CreateNamedPipe(pipeName, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                                      instances, PIPE_BUF_SIZE, PIPE_BUF_SIZE, 0, NULL); 

客户端管道以这种方式打开:

CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

我正在使用这些读取功能:

int readBytesPipeCommChannel(PipeCommChannelData* comm, uint32_t* amount)
    OVERLAPPED osRead;
    memset(&osRead, 0, sizeof(osRead));  
    osRead.hEvent = comm->readAsyncIOEvent;

    int err = 0;
    if(!ReadFile(comm->pipeH, comm->receiveBuffer, sizeof(comm->receiveBuffer), amount, &osRead))
    {   
        err = GetLastError();     
        if (err == ERROR_IO_PENDING)
        {
            if(WaitForSingleObject(osRead.hEvent, INFINITE))
            {
                GetOverlappedResult(comm->pipeH, &osRead, amount, TRUE);
            }
            else
            {
                CancelIo(comm->pipeH);
                return PIPE_EVENT_ERROR;
            }
        }
        else if(err != ERROR_BROKEN_PIPE)
        {
            return PIPE_READ_ERROR;
        }
    }
    if(err == ERROR_BROKEN_PIPE)
        return PIPE_BROKEN_ERR;

    return PIPE_OK;
}

最后但并非最不重要的是写函数:

int sendBytesPipeCommChannel(PipeCommChannelData* comm, const uint8_t* bytes, uint32_t amount)
{
    OVERLAPPED osWrite;
    memset(&osWrite, 0, sizeof(osWrite));  
    osWrite.hEvent = comm->writeAsyncIOEvent;

    uint32_t bytesWritten = 0; 
    for(uint32_t curPos = 0; curPos < amount; curPos += bytesWritten)
    {
        if(!WriteFile(comm->pipeH, &bytes[curPos], (amount - curPos), &bytesWritten, &osWrite))
        {
            if (GetLastError() != ERROR_IO_PENDING)
                return PIPE_WRITE_ERR; 

            if(!WaitForSingleObject(osWrite.hEvent, INFINITE))
            {
                CancelIo(comm->pipeH);
                return PIPE_EVENT_ERROR;
            }
        }
    }
    return PIPE_OK;
}

1 个答案:

答案 0 :(得分:0)

ReadFile的文档说:

  

如果使用hFile打开FILE_FLAG_OVERLAPPED,则以下条件有效:

     

lpNumberOfBytesRead参数应设置为NULL。使用GetOverlappedResult函数获取读取的实际字节数。

即使操作同步完成,这也适用。