其他分享
首页 > 其他分享> > c – 命名管道上的WriteFile有时会返回ERROR_NO_DATA

c – 命名管道上的WriteFile有时会返回ERROR_NO_DATA

作者:互联网

我有一个C程序正在创建一个命名管道来写入数据.一些客户报告了客户端连接到命名管道但服务器端无法写入数据的情况(使用ERROR_NO_DATA).

在我能找到的任何MSDN页面中都没有真正解释此错误代码;有没有人有任何想法如何解决这个问题?或者原因是什么?

打开代码:

ostringstream pipeName;
pipeName << "\\\\.\\pipe\\unique-named-pipe-" << GetCurrentProcessId();

pipeHandle = CreateNamedPipeA(
    pipeName.str().c_str(),              // pipe name
    PIPE_ACCESS_DUPLEX,                  // open mode
    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, // pipe mode
    PIPE_UNLIMITED_INSTANCES,            // max instances
    512,                                 // output buffer size
    512,                                 // input buffer size
    0,                                   // use default timeouts
    NULL);                               // security attributes

if (INVALID_HANDLE_VALUE == pipeHandle)
{
    THROW("Failed to create named pipe", GetLastError());
}

cout << "Pipe ready" << endl;

// Wait for a client to connect to the pipe        
BOOL status = ConnectNamedPipe(pipeHandle, NULL);

if (!status)
{
    DWORD lastError = GetLastError();

    if (ERROR_PIPE_CONNECTED != lastError)
    {
        THROW("Failed to wait for client to open pipe", lastError);
    }
    else
    {
        // Ignore, see MSDN docs for ConnectNamedPipe() for details.
    }
}

编写代码:

// response is a std::string
int writeOffset = 0;
int length = response.length();

while ((int) response.length() > writeOffset)
{
    DWORD bytesWritten;

    BOOL status = WriteFile(
        pipeHandle,
        response.c_str() + writeOffset,
        length - writeOffset,
        &bytesWritten,
        NULL);

    if (!status)
    {
        // This sometimes fails with ERROR_NO_DATA, why??
        THROW("Failed to send via named pipe", GetLastError());
    }

    writeOffset += bytesWritten;
}

扔宏

#define THROW(message, errorCode) \
{ \
    fprintf(stderr, "%s: line: %d file: %s error:0x%x\n", \
            message, __LINE__, __FILE__, errorCode); \
    fflush(stderr); \
    throw message; \
} \

谢谢!

解决方法:

查看WinError.h,它是定义此错误代码和其他错误代码的地方:

//
// MessageId: ERROR_NO_DATA
//
// MessageText:
//
// The pipe is being closed.
//
#define ERROR_NO_DATA                    232L

听起来客户端已经关闭了他们的管道末端 – 也许客户端代码认为它已经有了完整的字符串,关闭了他们的结束,而上面的代码继续尝试写?

标签:c,winapi,named-pipes
来源: https://codeday.me/bug/20191008/1871709.html