C++ 命名管道 IPC (七)

2014-11-24 02:37:40 · 作者: · 浏览: 13
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);
}
}

#pragma region Includes
#include
#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

// Response message from client to server. '\0' is appended in the end
// because the client may be a native C++ application that expects NULL
// termiated string.
#define RESPONSE_MESSAGE L"Default response from server"


BOOL CreatePipeSecurity(PSECURITY_ATTRIBUTES *);
void FreePipeSecurity(PSECURITY_ATTRIBUTES);


int wmain(int argc, wchar_t* argv[])
{
DWORD dwError = ERROR_SUCCESS;
PSECURITY_ATTRIBUTES pSa = NULL;
HANDLE hNamedPipe = INVALID_HANDLE_VALUE;

// Prepare the security attributes (the lpSecurityAttributes parameter in
// CreateNamedPipe) for the pipe. This is optional. If the
// 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