WriteFile в именованном канале иногда возвращает ERROR_NO_DATA - PullRequest
3 голосов
/ 24 мая 2011

У меня есть программа на 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.
    }
}

1011 *
*

Написание кода:

// 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; \
} \

Спасибо!

1 Ответ

3 голосов
/ 24 мая 2011

Глядя на WinError.h, где определены этот и другие коды ошибок:

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

Похоже, клиент уже закрыл свой конец канала - возможно, клиентский код думает, что он ужеполучил полную строку, закрывает их конец, а код выше продолжает пытаться записать?

...