c++ - WriteFile() block (通过命名管道从 C++ 客户端写入到 C# 服务器)

标签 c++ asynchronous block named-pipes writefile

我被困在这里了,请帮忙。 我有一个 C# 命名管道服务器,该管道由以下人员创建:

new NamedPipeServerStream(pipeName, PipeDirection.InOut, numThreads);

在 C++ 中,我创建了这样的客户端:

        m_hPipe = CreateFile( 
        strPipeName,            // Pipe name 
        GENERIC_READ |  GENERIC_WRITE,  // Read and write access 
        0,              // No sharing 
        NULL,               // Default security attributes
        OPEN_EXISTING,          // Opens existing pipe 
        FILE_FLAG_OVERLAPPED,    
        NULL);  

我将管道类型设置为 PIPE_READMODE_BYTE | PIPE_TYPE_BYTE
我编写了一个函数 WriteString() 来将字符串写入管道。函数大致是这样的:

    // Write the length of the string to the pipe (using 2 bytes)
    bool bResult = WriteFile(m_hPipe, buf, 2, &cbBytesWritten, NULL);

    // Write the string itself to the pipe
    bResult = WriteFile(m_hPipe, m_chSend, len, &cbBytesWritten, NULL);

    // Flush the buffer
    FlushFileBuffers(m_hPipe);

我对该函数进行了两次调用:

    WriteString(_T("hello server!"));   // message sent and the server saw it correctly
    WriteString(_T("goodbye server!")); // message not sent, coz WriteFile() blocked here

现在的问题是:程序在第二次 WriteString() 调用中的第一次 WriteFile() 调用时被阻塞。 只有当服务器关闭管道时,WriteFile() 调用才能返回错误。

这是可靠的可重现性。

什么阻止了这里的 WriteFile() 调用?我已经在使用 OVERLAPPED 文件标志。 管道缓冲区已满?我一直在从服务器端的管道读取数据。

非常感谢!

最佳答案

FILE_FLAG_OVERLAPPED 启用异步 I/O。它不会自动使任何操作异步、非阻塞或缓冲。

您需要使用 WriteFile 的第 5 个参数——传入一个 OVERLAPPED 结构,或者在完成时设置一个事件,或者将文件句柄与 I/O Completion Port 相关联.

关于c++ - WriteFile() block (通过命名管道从 C++ 客户端写入到 C# 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041582/

相关文章:

c - 读取器/写入器伪代码中潜在的竞争条件

滚动时出现 CSS/Chrome 白色 block

objective-c - 将 __block 与 self 一起使用

c++ - 编译时错误,参数被识别为引用

c++ - SFINAE + sizeof = 检测表达式是否编译

asynchronous - 异步 SQLalchemy : accessing eagerly-loaded empty relationship triggers new lazy-load, 引发错误

java - Java 中 Thrift 的异步请求

javascript - 无法在 return() React JSX 中使用 block

c++ - While 循环中的输入验证

c++ - VS2013 因可变参数模板特化而失败