WriteFile() 阻塞问题(通过命名管道从 C++ 客户端向 C# 服务器写入数据)

3

我被卡住了,请帮忙。 我有一个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文件标志。 管道缓冲区已满吗?我在服务器端一直从管道中读取。

非常感谢!

1个回答

3

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

您需要使用WriteFile的第5个参数——传递一个OVERLAPPED结构,其中包含一个完成时要设置的事件,或将文件句柄与I/O完成端口关联。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接