Named Pipes
Named pipes provide a mechanism for interprocess communication (IPC) between a pipe server and one or more pipe clients. They can be used locally or across a network and support message‑oriented or byte‑stream communication.
Functions
CreateNamedPipeConnectNamedPipeDisconnectNamedPipeCreateFile(client)ReadFileWriteFileSetNamedPipeHandleState
Syntax
HANDLE CreateNamedPipe(
LPCWSTR lpName,
DWORD dwOpenMode,
DWORD dwPipeMode,
DWORD nMaxInstances,
DWORD nOutBufferSize,
DWORD nInBufferSize,
DWORD nDefaultTimeOut,
LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
BOOL ConnectNamedPipe(
HANDLE hNamedPipe,
LPOVERLAPPED lpOverlapped
);
Parameters
| Parameter | Description |
|---|---|
| lpName | The unique pipe name, e.g., \\\\.\\pipe\\MyPipe. |
| dwOpenMode | Pipe open mode flags (e.g., PIPE_ACCESS_DUPLEX). |
| dwPipeMode | Data flow mode (e.g., PIPE_TYPE_MESSAGE). |
| nMaxInstances | Maximum number of simultaneous instances (use PIPE_UNLIMITED_INSTANCES). |
| nOutBufferSize | Size of the output buffer in bytes. |
| nInBufferSize | Size of the input buffer in bytes. |
| nDefaultTimeOut | Default timeout, in milliseconds. |
| lpSecurityAttributes | Security descriptor for the pipe (optional). |
Return Value
On success, returns a handle to the server end of the pipe. On failure, returns INVALID_HANDLE_VALUE. Use GetLastError for extended error information.
Remarks
- Named pipes can be used for local IPC or remote communication across a network.
- Pipe instances can be created dynamically; the server typically creates a new instance after each successful connection.
- When
PIPE_TYPE_MESSAGEis used, data is delivered as discrete messages; otherwise, it behaves as a byte stream. - Security attributes control who can access the pipe. Use
SECURITY_DESCRIPTORto restrict access.
Example (C++)
#include <windows.h>
#include <iostream>
int main()
{
const wchar_t* pipeName = L"\\\\.\\pipe\\SamplePipe";
HANDLE hPipe = CreateNamedPipeW(
pipeName,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
512, 512,
0,
nullptr);
if (hPipe == INVALID_HANDLE_VALUE) {
std::cerr << "CreateNamedPipe failed: " << GetLastError() << '\n';
return 1;
}
std::wcout << L"Waiting for client connection..." << std::endl;
BOOL connected = ConnectNamedPipe(hPipe, nullptr) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (!connected) {
std::cerr << "ConnectNamedPipe failed: " << GetLastError() << '\n';
CloseHandle(hPipe);
return 1;
}
const wchar_t* msg = L"Hello from server!";
DWORD bytesWritten;
WriteFile(hPipe, msg, (DWORD)(wcslen(msg) * sizeof(wchar_t)), &bytesWritten, nullptr);
wchar_t buffer[128];
DWORD bytesRead;
ReadFile(hPipe, buffer, sizeof(buffer), &bytesRead, nullptr);
buffer[bytesRead / sizeof(wchar_t)] = L'\0';
std::wcout << L"Received: " << buffer << std::endl;
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}