C++ 命名管道 IPC (二)

2014-11-24 02:37:40 · 作者: · 浏览: 11
new
// SECURITY_ATTRIBUTES structure to allow Authenticated Users read and
// write access to a pipe, and to allow the Administrators group full
// access to the pipe.
//
// PARAMETERS:
// * ppSa - output a pointer to a SECURITY_ATTRIBUTES structure that allows
// Authenticated Users read and write access to a pipe, and allows the
// Administrators group full access to the pipe. The structure must be
// freed by calling FreePipeSecurity.
//
// RETURN VALUE: Returns TRUE if the function succeeds..
//
// EXAMPLE CALL:
//
// PSECURITY_ATTRIBUTES pSa = NULL;
// if (CreatePipeSecurity(&pSa))
// {
// // Use the security attributes
// // ...
//
// FreePipeSecurity(pSa);
// }
//
BOOL CreatePipeSecurity(PSECURITY_ATTRIBUTES *ppSa)

//
// FUNCTION: CreatePipeSecurity(PSECURITY_ATTRIBUTES *)
//
// PURPOSE: The CreatePipeSecurity function creates and initializes a new
// SECURITY_ATTRIBUTES structure to allow Authenticated Users read and
// write access to a pipe, and to allow the Administrators group full
// access to the pipe.
//
// PARAMETERS:
// * ppSa - output a pointer to a SECURITY_ATTRIBUTES structure that allows
// Authenticated Users read and write access to a pipe, and allows the
// Administrators group full access to the pipe. The structure must be
// freed by calling FreePipeSecurity.
//
// RETURN VALUE: Returns TRUE if the function succeeds..
//
// EXAMPLE CALL:
//
// PSECURITY_ATTRIBUTES pSa = NULL;
// if (CreatePipeSecurity(&pSa))
// {
// // Use the security attributes
// // ...
//
// FreePipeSecurity(pSa);
// }
//

BOOL CreatePipeSecurity(PSECURITY_ATTRIBUTES *ppSa) 2.调用ConnectNamedPipe来等待客户端连接


[cpp] if (!ConnectNamedPipe(hNamedPipe, NULL))
{
if (ERROR_PIPE_CONNECTED != GetLastError())
{
dwError = GetLastError();
wprintf(L"ConnectNamedPipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}
}

if (!ConnectNamedPipe(hNamedPipe, NULL))
{
if (ERROR_PIPE_CONNECTED != GetLastError())
{
dwError = GetLastError();
wprintf(L"ConnectNamedPipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}
}
3.通过调用ReadFile和WriteFile从管道中读出客户端请求并写入响应数据[cpp] view plaincopyprint //
// Receive a request from client.
//

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

fFinishRead = ReadFile(
hNamedPipe, // Handle of the pipe
chRequest, // Buffer to receive data
cbRequest, // Size of buffer in bytes
&cbRead, // Number of bytes read
NULL // Not overlapped I/O
);

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 client: \"%s\"\n", cbRead, chRequest);

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

//
// Send a response