C++ 命名管道 IPC (五)

2014-11-24 02:37:40 · 作者: · 浏览: 12
lpSecurityAttributes parameter of CreateNamedPipe is NULL, the named
// pipe gets a default security descriptor and the handle cannot be
// inherited. The ACLs in the default security descriptor of a pipe grant
// full control to the LocalSystem account, (elevated) administrators,
// and the creator owner. They also give only read access to members of
// the Everyone group and the anonymous account. However, if you want to
// customize the security permission of the pipe, (e.g. to allow
// Authenticated Users to read from and write to the pipe), you need to
// create a SECURITY_ATTRIBUTES structure.
if (!CreatePipeSecurity(&pSa))
{
dwError = GetLastError();
wprintf(L"CreatePipeSecurity failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

// Create the named pipe.
hNamedPipe = CreateNamedPipe(
FULL_PIPE_NAME, // Pipe name.
PIPE_ACCESS_DUPLEX, // The pipe is duplex; both server and
// client processes can read from and
// write to the pipe
PIPE_TYPE_MESSAGE | // Message type pipe
PIPE_READMODE_MESSAGE | // Message-read mode
PIPE_WAIT, // Blocking mode is enabled
PIPE_UNLIMITED_INSTANCES, // Max. instances
BUFFER_SIZE, // Output buffer size in bytes
BUFFER_SIZE, // Input buffer size in bytes
NMPWAIT_USE_DEFAULT_WAIT, // Time-out interval
pSa // Security attributes
);

if (hNamedPipe == INVALID_HANDLE_VALUE)
{
dwError = GetLastError();
wprintf(L"Unable to create named pipe w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"The named pipe (%s) is created.\n", FULL_PIPE_NAME);

// Wait for the client to connect.
wprintf(L"Waiting for the client's connection...\n");
if (!ConnectNamedPipe(hNamedPipe, NULL))
{
if (ERROR_PIPE_CONNECTED != GetLastError())
{
dwError = GetLastError();
wprintf(L"ConnectNamedPipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}
}
wprintf(L"Client is connected.\n");

//
// 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 from server to client.
//

wchar_t chResponse[] = RESPONSE_MESSAGE;
DWORD cbResponse, cbWritt