C++ 命名管道 IPC (三)

2014-11-24 02:37:40 · 作者: · 浏览: 17
leanup;
}

// All pipe instances are busy, so wait for 5 seconds.
if (!WaitNamedPipe(FULL_PIPE_NAME, 5000))
{
dwError = GetLastError();
wprintf(L"Could not open pipe: 5 second wait timed out.");
goto Cleanup;
}
}

// Set the read mode and the blocking mode of the named pipe. In this
// sample, we set data to be read from the pipe as a stream of messages.
DWORD dwMode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL))
{
dwError = GetLastError();
wprintf(L"SetNamedPipeHandleState failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

//
// Send a request from client to server
//

wchar_t chRequest[] = REQUEST_MESSAGE;
DWORD cbRequest, cbWritten;
cbRequest = sizeof(chRequest);

if (!WriteFile(
hPipe, // Handle of the pipe
chRequest, // Message to be written
cbRequest, // Number of bytes to write
&cbWritten, // Number of bytes written
NULL // Not overlapped
))
{
dwError = GetLastError();
wprintf(L"WriteFile to pipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"Send %ld bytes to server: \"%s\"\n", cbWritten, chRequest);

//
// Receive a response from server.
//

BOOL fFinishRead = FALSE;
do
{
wchar_t chResponse[BUFFER_SIZE];
DWORD cbResponse, cbRead;
cbResponse = sizeof(chResponse);

fFinishRead = ReadFile(
hPipe, // Handle of the pipe
chResponse, // Buffer to receive the reply
cbResponse, // Size of buffer in bytes
&cbRead, // Number of bytes read
NULL // Not overlapped
);

if (!fFinishRead && ERROR_MORE_DATA != GetLastError())
{
dwError = GetLastError();
wprintf(L"ReadFile from pipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"Receive %ld bytes from server: \"%s\"\n", cbRead, chResponse);

} while (!fFinishRead); // Repeat loop if ERROR_MORE_DATA

Cleanup:

// Centralized cleanup for all allocated resources.
if (hPipe != INVALID_HANDLE_VALUE)
{
CloseHandle(hPipe);
hPipe = INVALID_HANDLE_VALUE;
}

return dwError;
}