C++ 命名管道 IPC (九)

2014-11-24 02:37:40 · 作者: · 浏览: 16
L;
PSECURITY_ATTRIBUTES pSa = NULL;

// Define the SDDL for the security descriptor.
PCWSTR szSDDL = L"D:" // Discretionary ACL
L"(A;OICI;GRGW;;;AU)" // Allow read/write to authenticated users
L"(A;OICI;GA;;;BA)"; // Allow full control to administrators

if (!ConvertStringSecurityDescriptorToSecurityDescriptor(szSDDL,
SDDL_REVISION_1, &pSd, NULL))
{
fSucceeded = FALSE;
dwError = GetLastError();
goto Cleanup;
}

// Allocate the memory of SECURITY_ATTRIBUTES.
pSa = (PSECURITY_ATTRIBUTES)LocalAlloc(LPTR, sizeof(*pSa));
if (pSa == NULL)
{
fSucceeded = FALSE;
dwError = GetLastError();
goto Cleanup;
}

pSa->nLength = sizeof(*pSa);
pSa->lpSecurityDescriptor = pSd;
pSa->bInheritHandle = FALSE;

*ppSa = pSa;

Cleanup:
// Clean up the allocated resources if something is wrong.
if (!fSucceeded)
{
if (pSd)
{
LocalFree(pSd);
pSd = NULL;
}
if (pSa)
{
LocalFree(pSa);
pSa = NULL;
}

SetLastError(dwError);
}

return fSucceeded;
}


//
// FUNCTION: FreePipeSecurity(PSECURITY_ATTRIBUTES)
//
// PURPOSE: The FreePipeSecurity function frees a SECURITY_ATTRIBUTES
// structure that was created by the CreatePipeSecurity function.
//
// PARAMETERS:
// * pSa - pointer to a SECURITY_ATTRIBUTES structure that was created by
// the CreatePipeSecurity function.
//
void FreePipeSecurity(PSECURITY_ATTRIBUTES pSa)
{
if (pSa)
{
if (pSa->lpSecurityDescriptor)
{
LocalFree(pSa->lpSecurityDescriptor);
}
LocalFree(pSa);
}
}CppNamedPipeClient.cpp


[cpp] #pragma region Includes
#include
#include
#pragma endregion


// The full name of the pipe in the format of \\servername\pipe\pipename.
#define SERVER_NAME L"."
#define PIPE_NAME L"SamplePipe"
#define FULL_PIPE_NAME L"\\\\" SERVER_NAME L"\\pipe\\" PIPE_NAME

#define BUFFER_SIZE 1024

// Request message from client to server.
#define REQUEST_MESSAGE L"Default request from client"


int wmain(int argc, wchar_t* argv[])
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
DWORD dwError = ERROR_SUCCESS;

// Try to open the named pipe identified by the pipe name.
while (TRUE)
{
hPipe = CreateFile(
FULL_PIPE_NAME, // Pipe name
GENERIC_READ | GENERIC_WRITE, // Read and write access
0, // No sharing
NULL, // Default security attributes
OPEN_EXISTING, // Opens existing pipe
0, // Default attributes
NULL // No template file
);

// If the pipe handle is opened successfully ...
if (hPipe != INVALID_HANDLE_VALUE)
{
wprintf(L"The named pipe (%s) is connected.\n", FULL_PIPE_NAME);
break;
}

dwError = GetLastError();

// Exit if an error other than ERROR_PIPE_BUSY occurs.
if (ERROR_PIPE_BUSY != dwError)
{
wprintf(L"Unable to open named pipe w/err 0x%08lx\n", dwError);
goto C