开发者

WriteFile() blocks (writing from C++ client to C# server via named pipe )

开发者 https://www.devze.com 2023-03-06 12:40 出处:网络
I am stuck here, please help. I have a C# named pipe server, the pipe is created by: new NamedPipeServerStream(pipeName, PipeDirection.InOut, numThreads);

I am stuck here, please help. I have a C# named pipe server, the pipe is created by:

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

In C++ I created the client like this:

        m_hPipe = CreateFile( 
        strPipeName,            // Pipe name 
        GENERIC_READ |  GENERIC_WRITE,  // Read and write access 
       开发者_如何学C 0,              // No sharing 
        NULL,               // Default security attributes
        OPEN_EXISTING,          // Opens existing pipe 
        FILE_FLAG_OVERLAPPED,    
        NULL);  

I set the pipe type to PIPE_READMODE_BYTE | PIPE_TYPE_BYTE

I wrote a function WriteString() to write a string to the pipe. The function is roughly like this:

    // 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);

I made two calls to the function:

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

Now the problem is: the program is blocked at the first WriteFile() call in the second WriteString() call. Only when the pipe is closed by the server can the WriteFile() call return with an error.

This is reliably reproducible.

What is blocking the WriteFile() call here? I am already using the OVERLAPPED file flag. Pipe buffer is full? I keep reading from the pipe on the server side.

Thanks a lot!


FILE_FLAG_OVERLAPPED enables asynchronous I/O. It does not automatically make any operations asynchronous, non-blocking, or buffered.

You need to use the 5th parameter of WriteFile – pass in an OVERLAPPED structure, either with an event to set on completion, or associate the file handle with an I/O Completion Port.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号